package com.nari.ysphd.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.intel.webrtc.base.ActionCallback;
import com.intel.webrtc.base.ClientContext;
import com.intel.webrtc.base.LocalCameraStream;
import com.intel.webrtc.base.LocalCameraStreamParameters;
import com.intel.webrtc.base.MediaCodec.VideoCodec;
import com.intel.webrtc.base.RemoteStream;
import com.intel.webrtc.base.Stream;
import com.intel.webrtc.base.WoogeenException;
import com.intel.webrtc.base.WoogeenIllegalArgumentException;
import com.intel.webrtc.conference.PublishOptions;
import com.intel.webrtc.conference.RecordOptions;
import com.intel.webrtc.conference.SubscribeOptions;
import com.intel.webrtc.conference.User;
import com.jeremyfeinstein.conference.ConferenceStreamView;
import com.jeremyfeinstein.conference.CustomDialog;
import com.jeremyfeinstein.conference.CustomSurfaceRenderer;
import com.jeremyfeinstein.conference.NewZoomDialogManger;
import com.jeremyfeinstein.conference.YCHSConferenceClient;
import com.jeremyfeinstein.conference.ZoomStreamView;
import com.jeremyfeinstein.event.AddAudioStreamEvent;
import com.jeremyfeinstein.event.AddVideoStreamEvent;
import com.jeremyfeinstein.event.AllowTalkEvent;
import com.jeremyfeinstein.event.ApplyForSpeakerEvent;
import com.jeremyfeinstein.event.AttacheFileEvent;
import com.jeremyfeinstein.event.ChangeHostAssistListEvent;
import com.jeremyfeinstein.event.ChangeUserRoleEvent;
import com.jeremyfeinstein.event.ChatMessageEvent;
import com.jeremyfeinstein.event.CloseAudioStreamEvent;
import com.jeremyfeinstein.event.CloseMixStreamEvent;
import com.jeremyfeinstein.event.CloseVideoStreamEvent;
import com.jeremyfeinstein.event.DisableAudioEvent;
import com.jeremyfeinstein.event.DoubleClickListener;
import com.jeremyfeinstein.event.EditAliasNameEvent;
import com.jeremyfeinstein.event.EnableAudioEvent;
import com.jeremyfeinstein.event.EndMeetingEvent;
import com.jeremyfeinstein.event.ExitConferenceEvent;
import com.jeremyfeinstein.event.ExitMeetingEvent;
import com.jeremyfeinstein.event.ForbidTalkEvent;
import com.jeremyfeinstein.event.GetMeetingUserListEvent;
import com.jeremyfeinstein.event.HDMsgEvent;
import com.jeremyfeinstein.event.JoinEvent;
import com.jeremyfeinstein.event.OnStreamRemoveEvent;
import com.jeremyfeinstein.event.ShareDeskTopEvent;
import com.jeremyfeinstein.event.ShareVideoEvent;
import com.jeremyfeinstein.event.StartRecordEvent;
import com.jeremyfeinstein.event.StopShareEvent;
import com.jeremyfeinstein.event.TempRoomEvent;
import com.jeremyfeinstein.exception.YchsException;
import com.jeremyfeinstein.gson.FileEntity;
import com.jeremyfeinstein.gson.JoinResponse;
import com.jeremyfeinstein.gson.MeetingUser;
import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.listener.OnSocketListener;
import com.jeremyfeinstein.okhttputil.callback.FileCallBack;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;
import com.jeremyfeinstein.utils.APPUtils;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.ConferenceApp;
import com.jeremyfeinstein.utils.ConfigUtil;
import com.jeremyfeinstein.utils.ResolverUtil;
import com.jeremyfeinstein.utils.SwitchToIOThread;
import com.jeremyfeinstein.utils.SwitchToMainThread;
import com.jeremyfeinstein.utils.ToastUtil;
import com.jeremyfeinstein.utils.YCHSInstance;
import com.jeremyfeinstein.utils.YCHSWebSocketAPI;
import com.jeremyfeinstein.utils.YCHShttpAPI;
import com.nari.ysphd.MyApp;
import com.nari.ysphd.R;
import com.nari.ysphd.adapter.ContentPageAdapter;
import com.nari.ysphd.util.ActivityManager;
import com.nari.ysphd.util.AndroidFileUtil;
import com.nari.ysphd.util.FileSizeUtil;
import com.nari.ysphd.util.PictureUtil;
import com.nari.ysphd.util.log.HDMsgUtils;
import com.nari.ysphd.util.log.MLog;
import com.nari.ysphd.view.AliasNameDialog;
import com.nari.ysphd.view.ConferenceChatView;
import com.nari.ysphd.view.MeetingScreenGrid;
import com.nari.ysphd.view.PopDialog;
import com.nari.ysphd.view.Progress_Dialog;
import com.nari.ysphd.view.UserSelectDialog;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;
import org.webrtc.EglBase;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import nari.mip.core.Platform;
import okhttp3.Call;

public class ConferenceRoomUI extends BaseActivity implements OnClickListener, View.OnTouchListener {
    private static final String TAG = ConferenceRoomUI.class.getSimpleName();
    public static final String MCU_ROOMID = "MCU_ROOMID";
    public static final String MCU_ROLE = "MCU_ROLE";
    public static final String MEETING_ID = "MEETING_ID";
    public static final String MEETING_NAME = "MEETING_NAME";
    public static final String MEETING_SART_TIME = "MEETING_SART_TIME";
    public static final String MEETING_TYPE = "MEETING_TYPE";
    public static final int GET_PIC_FROM_CAMERA = 0x123;
    public static final int GET_PIC_FROM_GALLERY = 0X124;
    public static final int EDIT_METTING = 0x125;
    private static int AUTO_LOGOUT_ACTIVITY = 0;

    //会议界面文件存放地址
    private String fileDir = "ysphd_files";
    private String ATTACHEFILEPATH = "";
    private ImageView iv_back;
    private ImageView iv_menu_room;
    private TextView tv_tabusers, tv_tabfiles;
    // Spinner sp_toperson;
    private MyAdapter myAdapter;
    private FileAdapter fileAdapter;
    private ListView lv_lvpersion;
    private ListView lv_lvfile;
    private LinearLayout ll_fileLayout;
    // private ListView lv_chart;
    // private MyAdapterchart mychart;
    DrawerLayout mDrawerLayout;
    private ImageView iv_open;
    private ImageView iv_close;
    private boolean isExitShareVideo = false;
    private boolean isEnlargeShareVideo = false;
    // webrtc
    private MeetingScreenGrid meetingScreenGrid;
    private ConferenceStreamView conferenceStreamView;
    private ZoomStreamView zoomStreamView;
    private EglBase rootEglBase;
    private LocalCameraStream localStream;
    private TextView room_name;
    private String meetingName;
    private String meetingStartTime;
    private String joinFlag, bFlag;
    private View content_frame;
    private View id_drawerlayout2;
    private List<String> applySpeakerList;
    private MeetingUser meetingUser;
    // 附件列表
    private List<FileEntity> fileList;
    private LinearLayout ll_tackphoto;
    private LinearLayout ll_gallery;
    private File mFile;// 存储图片的文件
    private boolean enlargeFlag = false;
    private ProgressDialog progressDialog;
    private long mLastTime;
    private long mCurTime;
    private boolean toolbarShowFlag = false;
    private ConferenceChatView mConferenceChatView;
    private Timer timer;
    private Timer netTimer;
    private int maximumVideoBandwidth = 300;
    private int netSpeed = 30;//不同分辨率判断网速低参考值
    private int videoRate = 3;
    private int netCheckLowCount = 0;
    private int netCheckLowCount2 = 0;//用于检查下行网速计数
    private PopDialog qualityPopDialog;
    private boolean isShareDesktop = false;
    private boolean isOpenCameraOrNot = true;
    private int isEventUserListener = 1;
    private WindowManager vm;
    private AlertDialog tempDialog = null;
    private boolean isVideoOpen = false;
    private int width, height;
    private int attendanceNm = 0;
    //    private ScrollView remoteScrollView;
    private ArrayList<View> pageViews;
    private ViewPager viewPager;
    private View conferenceView, zoomView, controlDeviceView;
    private String status, userCode;
    private TextView confrenceName;
    //默认静音
    private boolean checksound = true;
    private boolean checkMic = true;
    //默认非最大化
    private boolean openbigVideo = false;
    private boolean isExit;
    AliasNameDialog aliasNameDialog;
    private String mUserSN;
    private ImageView upView, rightView, downView, leftView, zoomInView, zoomOutView;
    private ListView lv_lvfile2;
    private boolean IsOut = false;


    private View localVideoDescView2;
    private LinearLayout linearLayout;
    private View btn_09;
    private View menuliner;
    private View btn_03;
    private View btn_01;
    private View btn_06;
    private View btn_07;
    private ImageView speakerImg, speak_img, video_img;
    private TextView tx_open;
    private ListView persion;
    private TextView tabfiles;
    private TextView tabchat;
    private View btn_10;
    private LinearLayout chat_linear;
    private LinearLayout linear_fiel;
    private int muta = 0;
    private View localVideoDescView1;
    private List<MeetingUser> userList;
    private TimerTask timerTask;
    private TimerTask netTimerTask;
    private ImageView audio_img;
    private LinearLayout chat_view;
    private ImageView addfile;
    private LinearLayout uploadFile;
    private LinearLayout uppic, upphoto, upfile, mune;
    private TextView chatback;
    private boolean IsNomute = true;

    private static final String ADD_AUDIO_STREAM = "addAudioStream";
    private static final String DELETE_AUDIO_STREAM = "deleteAudioStream";
    private static final String ADD_VIDEO_STREAM = "addVideoStream";
    private static final String DELETE_VIDEO_STREAM = "deleteVideoStream";
    private static final String ALLOW = "allow";
    private static final String FORBID = "forbid";

    private String audioStatus = ADD_AUDIO_STREAM; //audioStatus： addAudioStream   deleteAudioStream  //音频状态
    private String videoStatus = ADD_VIDEO_STREAM; //videoStatus： addVideoStream   deleteVideoStream  //视频状态

    private String audioForbid = ALLOW; //audioForbid： allow  forbid //音频权限
    private String videoForbid = ALLOW; //videoForbid： allow  forbid //视频权限

    /**
     * 用来检查保存会议在线的定时器
     */
    private ScheduledExecutorService checkMeetingonlineExecutor = Executors.
            newSingleThreadScheduledExecutor();

    private ScheduledFuture<?> checkMeetingOnlineFuture;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
//        userCode = YCHSInstance.getApp().getLoginUser().getUSER_CODE();
//        setCurrentActivity("1");
        AudioManager audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
        audioManager.setSpeakerphoneOn(true);
        // 20171025  设置音量模式
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        // 保持屏幕一直处于唤醒状态
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        progressDialog = ProgressDialog.show(this, null, "正在加载...");
        timer = new Timer();
        timerTask = new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("当前网络状态不稳定，请重新加入会议！");
                        leave();
                    }
                });
            }
        };
        registerHeadsetPlugReceiver();
        timer.schedule(timerTask, 20 * 1000);
        conferenceStreamView.setRoom(YCHSConferenceClient.getInstance().getConferenceClient());
        zoomStreamView.setRoom(YCHSConferenceClient.getInstance().getConferenceClient());
        Logger.e("onCreate" + "进入互动室!");
        YCHSConferenceClient.getInstance().joinRoom(ConferenceRoomUI.this,
                "U" + YCHSInstance.getInstance().getLoginUser().getUSER_CODE(), joinFlag, new ActionCallback<User>() {
                    @Override
                    public void onSuccess(User myself) {
                        Log.d(TAG, "My client Id: " + myself.getId());
                        MLog.e(TAG, "onSuccess: " + "My client Id: " + myself.getId());
                        HDMsgUtils.start();
                    }

                    @Override
                    public void onFailure(final WoogeenException e) {
                        Logger.e("joinroom" + "exception :" + e.getMessage());
                        MLog.e("joinroom" + "exception :" + e.getMessage());
                        runOnUiThread(new Runnable() {
                            public void run() {
//                                showNormalDialog(e.getMessage());
                                ToastUtil.showLong(MyApp.getApp(), "加入会议失败");
                                leave();
                            }
                        });
                    }
                });


        ATTACHEFILEPATH = getExternalCacheDir() + File.separator + fileDir;
        File file = new File(ATTACHEFILEPATH);
        if (!file.exists()) {
            file.mkdir();
        }

        YCHSWebSocketAPI.getInstance().setOnSocketListener(new OnSocketListener() {
            @Override
            public void onError(int code, final YchsException e) {
                SwitchToMainThread.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showLong(MyApp.getApp(), e.getMessage());
                        finish();
                    }
                });
            }

            @Override
            public void onConnectSuccess() {
                //latch.countDown();
            }
        });

        checkMeetingOnlineFuture = checkMeetingonlineExecutor.
                scheduleAtFixedRate(checkMeetingOnlingRunnable,
                        1, 1, TimeUnit.MINUTES);
    }

    Runnable checkMeetingOnlingRunnable = new Runnable() {
        @Override
        public void run() {
            YCHSWebSocketAPI.getInstance().keepMeetingByIntervalTime();
        }
    };


    private void showNormalDialog(String message) {
        Activity activity = ConferenceRoomUI.this;
        while (activity.getParent() != null) {
            activity = activity.getParent();
        }
        try {
            Builder dialog = new Builder(activity);
            dialog.setMessage(message);
            tempDialog = dialog.create();
            tempDialog.setButton("确定", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub
                    finish();
                }
            });
            tempDialog.show();
        } catch (Exception e) {
            dismissTempDialog();
        }
    }

    private void dismissTempDialog() {
        if (null != tempDialog) {
            tempDialog.dismiss();
        }
    }

    private void dismissprossDialog() {
        if (null != progressDialog) {
            progressDialog.dismiss();
        }
    }


    private void showAdjustResolutionDialog() {
        if (videoRate == 1) {
            Toast.makeText(getApplicationContext(), "当前网络状况较差！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (qualityPopDialog != null && qualityPopDialog.isShowing()) {
            return;
        }
        qualityPopDialog = new PopDialog(ConferenceRoomUI.this);
        qualityPopDialog.setPopMessage("当前网络状况较差，是否降低视频画质?");
        qualityPopDialog.setConfirmOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                videoRate--;
                publishLocalStream(videoRate, null);
                qualityPopDialog.dismiss();
            }
        });
        qualityPopDialog.showAtLocation(content_frame, Gravity.CENTER, 0, 0);
    }


    private void initVideoStreamsViews() {
        viewPager.setCurrentItem(0, false);
        localVideoDescView2 = conferenceView.findViewById(R.id.descView2);
//        localVideoDescView1 = conferenceView.findViewById(R.id.descView1);
        confrenceName = (TextView) conferenceView.findViewById(R.id.confrenceName);
        bFlag = getIntent().getStringExtra("ballFlag");
        conferenceStreamView = new ConferenceStreamView((LinearLayout) conferenceView.findViewById(R.id.llRemoteView));
        zoomStreamView = new ZoomStreamView((LinearLayout) zoomView.findViewById(R.id.zoomView));
//        remoteScrollView = (ScrollView) conferenceView.findViewById(R.id.remote_stream_scroll);
//        remoteScrollView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                return true;//禁止滚动
//            }
//        });
        conferenceView.findViewById(R.id.llRemoteView).setOnClickListener(this);


        fixResolution(vm, width, height);
        meetingScreenGrid = new MeetingScreenGrid(
                (LinearLayout) conferenceView.findViewById(R.id.llScreenGridView),

                new DoubleClickListener() {
                    @Override
                    public void onDoubleClick(final int i) {
                        List<RemoteStream> streams = YCHSConferenceClient.getInstance().getRemoteStreams();
                        Log.e("GetTime", "视频流的个数" + streams.size());
                        for (final RemoteStream stream : streams) {
                            YCHSConferenceClient.getInstance().getRegion(stream, new ActionCallback<String>() {

                                @Override
                                public void onFailure(WoogeenException arg0) {
                                }

                                @Override
                                public void onSuccess(final String arg0) {
                                    if (Integer.valueOf(arg0) == i && meetingScreenGrid.isNotVisible(i)) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
//														findViewById(R.id.zoomView).setOnClickListener(this);
                                                content_frame.setBackgroundColor(getResources().getColor(R.color.default_person_bg2));
//														meetingLocalStreamView.getContainer().setVisibility(View.GONE);
                                                enlargeFlag = true;
                                                if (YCHSConferenceClient.getInstance().hasConferenceControlPermission() && YCHSInstance.getInstance().getMode() == 1) {
                                                    final PopDialog popDialog = new PopDialog(ConferenceRoomUI.this);
                                                    popDialog.setPopMessage("是否共享视频?");
                                                    popDialog.setConfirmOnClickListener(new OnClickListener() {
                                                        @Override
                                                        public void onClick(
                                                                View v) {
                                                            content_frame.setBackgroundColor(getResources().getColor(R.color.gray5));
                                                            viewPager.setCurrentItem(1, false);
//																			meetingLocalStreamView
//																					.playLocalStream(localStream);
                                                            meetingScreenGrid.getContainer().setVisibility(View.GONE);
                                                            normalResolution(vm, width, height);
                                                            zoomStreamView.playRemoteStream(stream, checksound);
                                                            YCHSConferenceClient.getInstance().shareVideo(stream.getId());
                                                            popDialog.dismiss();
                                                            isExitShareVideo = true;
                                                            if (YCHSInstance.getInstance().getRecorderId() != null) {
                                                                RecordOptions opt = new RecordOptions();
                                                                opt.setRecorderId(YCHSInstance.getInstance().getRecorderId());
                                                                opt.setAudioStreamId(stream.getId());
                                                                opt.setVideoStreamId(stream.getId());
                                                                YCHSConferenceClient.getInstance().startRecorder(opt, null);
                                                            }
                                                        }
                                                    });
                                                    popDialog.showAtLocation(content_frame, Gravity.CENTER, 0, 0);
                                                } else {
//                                                            conferenceStreamView.stopRemoteStream();
                                                    content_frame.setBackgroundColor(getResources().getColor(R.color.gray5));
                                                    viewPager.setCurrentItem(1, false);
                                                    viewPager.removeViewAt(0);
                                                    meetingScreenGrid.getContainer().setVisibility(View.GONE);
                                                    normalResolution(vm, width, height);
                                                    zoomStreamView.playRemoteStream(stream, checksound);
//                                                    Toast.makeText(ConferenceRoomUI.this, "当前视频已放大！", Toast.LENGTH_SHORT).show();
                                                    isExitShareVideo = true;
                                                    isEnlargeShareVideo = true;
                                                           /* MeetingUser meetingUser = YCHSConferenceClient.getApp().getMeetringUserByStreamId(stream.getId());
                                                            userCode = meetingUser.getUserSN();
                                                            boolean ballFlag = isBuKongQiu(userCode);
                                                            if (ballFlag) {
                                                                //说明是布控球显示操作按钮
                                                                controlDeviceView.setVisibility(View.VISIBLE);
                                                            } else {
                                                                controlDeviceView.setVisibility(View.GONE);
                                                            }*/
                                                }
                                            }
                                        });
                                        return;
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onToch(final String aliasName, final String userSN) {

                    }
                });
        fixLocalViewResolution(vm, width, height);

    }


    public void dissLocalCameraView() {
        if (meetingScreenGrid != null) {
            meetingScreenGrid.setLocalCameraViewGone();
        }
    }

    private void fixAllResolution(WindowManager vm, int width, int height) {
//        Log.i(TAG, "weight = " + width + "h= " + height);
//        LayoutParams layoutparams = (LayoutParams) content_frame.getLayoutParams();
//        if ((width / height) > (16 / 9)) {
//            layoutparams.height = height;
//            layoutparams.width = (height * 16 / 9);
//        } else {
//            layoutparams.width = width;
//            layoutparams.height = (width * 9 / 16);
//        }
//        content_frame.setLayoutParams(layoutparams);
//        RelativeLayout.LayoutParams layoutparams3 = (RelativeLayout.LayoutParams) meetingScreenGrid.getContainer().getLayoutParams();
//        layoutparams3.height = layoutparams.height;
//        layoutparams3.width = layoutparams.width;
//        meetingScreenGrid.getContainer().setLayoutParams(layoutparams3);

    }

    private void fixResolution(WindowManager vm, int width, int height) {
//        Log.i(TAG, "w = " + width + "h= " + height);
//        RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) conferenceStreamView.getContainer().getLayoutParams();
//        calcWidthandHeight(width, height, layoutparams);
//        layoutparams.setMargins(layoutparams.width / 2, 0, 0, 0);
//        conferenceStreamView.getContainer().setLayoutParams(layoutparams);

//        int screenWidth = CommonUtil.getScreenWidth(ConferenceRoomUI.this);
//        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) conferenceStreamView.getContainer().getLayoutParams();
//        int translationX = Math.abs((params2.width / 2) - screenWidth);
//        params2.setMarginEnd(-translationX);
//        conferenceStreamView.getContainer().setLayoutParams(params2);
    }

    private void fixLocalViewResolution(WindowManager vm, int width, int height) {
//        Log.i(TAG, "w = " + width + "h= " + height);
//
//        RelativeLayout.LayoutParams layoutparams7 = (RelativeLayout.LayoutParams) localVideoDescView2.getLayoutParams();
//        layoutparams7.width = width / 2;
//        localVideoDescView2.setLayoutParams(layoutparams7);

    }

    private void calcWidthandHeight(int width, int height, RelativeLayout.LayoutParams layoutparams) {
//        if ((width / height) > (16 / 9)) {
//            layoutparams.height = height;
//            layoutparams.width = (height * 16 / 9);
//        } else {
//            layoutparams.width = width;
//            layoutparams.height = (width * 9 / 16);
//        }
    }

    private void normalResolution(WindowManager vm, int width, int height) {
        RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) conferenceStreamView.getContainer().getLayoutParams();
        calcWidthandHeight(width, height, layoutparams);
        layoutparams.setMargins(0, 0, layoutparams.width / 2, 0);
        conferenceStreamView.getContainer().setLayoutParams(layoutparams);
    }

    private void initAudioControl() {
        try {
            Properties p = new Properties();
            InputStream s = this.getAssets().open("audio_control.properties");
            p.load(s);

            ClientContext.setAudioControlEnabled(Boolean.parseBoolean(p.getProperty("enable_audio_control")));
            ClientContext.setAudioLevelOverloud(Integer.parseInt(p.getProperty("audio_level_overloud")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_meetingroom);
        vm = ConferenceRoomUI.this.getWindowManager();
        width = vm.getDefaultDisplay().getWidth();
        height = vm.getDefaultDisplay().getHeight();
    }


    @Override
    protected void onDestroy() {

        HDMsgUtils.stop();

        EventBus.getDefault().unregister(this);
        if (aliasNameDialog != null) {
            aliasNameDialog.dismiss();
            aliasNameDialog = null;
        }
        checkMeetingOnlineFuture.cancel(true);
        YCHSWebSocketAPI.getInstance().closeSocket();

//        YCHSInstance.resetInstance();
        conferenceStreamView.pause();
        // meetingShareStreamView.pause();
//        meetingLocalStreamView.pause();
        exitMeeting();
        unregisterReceiver(mHeadSetReceiver);
//        unregisterReceiver(conReceiver);
//        setCurrentActivity("0");
        conferenceRemove();

        AppConstants.SERVER_URL = AppConstants.REQUEST_MODE
                + ConfigUtil.getInstance().getRemoteUrl() + ":"
                + ConfigUtil.getInstance().getRemotePort();
        if (localStream != null) {
            localStream.close();
            checkMic = true;
            openPTTAudio();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
        }
        closeNetTimer();

        dismissTempDialog();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        if (qualityPopDialog != null && qualityPopDialog.isShowing()) {
            qualityPopDialog.dismiss();
            qualityPopDialog = null;
        }
//        closesocket();
        YCHSConferenceClient.getInstance().leave(null);
        YCHSConferenceClient.getInstance().getChatMessages().clear();
        super.onDestroy();
    }

    private void closeNetTimer() {
        if (netTimer != null) {
            netTimer.cancel();
            netTimer = null;
            if (netTimerTask != null) {
                netTimerTask.cancel();
                netTimerTask = null;
            }
        }
    }

    @Override
    protected void onPause() {
        // conferenceStreamView.pause();
        // meetingShareStreamView.pause();
//        meetingLocalStreamView.pause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        // conferenceStreamView.resume();
        // meetingShareStreamView.resume();
        if (vm == null) {
            vm = ConferenceRoomUI.this.getWindowManager();
        }
//        meetingLocalStreamView.resume();
//        setCurrentActivity("1");


        super.onResume();
    }


    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");
//        registerReceiver(mHeadSetReceiver, intentFilter);
        registerReceiver(mHeadSetReceiver, intentFilter, "permission.ALLOW_BROADCAST", null);

        // for bluetooth headset connection receiver
//        IntentFilter bluetoothFilter = new IntentFilter();
//        intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
//        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
//        registerReceiver(mHeadSetReceiver, bluetoothFilter);
    }

    //耳机  20171025新增  线控耳机和蓝牙监听
    private static BroadcastReceiver mHeadSetReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
            if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
                int state = intent.getIntExtra("state", -1);
                switch (state) {
                    case 0:
                        audioManager.setSpeakerphoneOn(true);
                        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                        Log.e("20171025", "耳机拔出来");
                        break;
                    case 1:
                        audioManager.setSpeakerphoneOn(false);
                        audioManager.setMode(AudioManager.MODE_NORMAL);
                        Log.e("20171025", "耳机插人");

                        break;
                    default:
                        Log.d("ConferenceHomeActivity", "未知状态");
                        break;
                }

            } /*else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                if (BluetoothProfile.STATE_DISCONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
//                    isheadset--; //Bluetooth headset is now disconnected
                    audioManager.setSpeakerphoneOn(true);
                } else {
//                    isheadset++;
                    audioManager.setSpeakerphoneOn(true);
                   *//* audioManager.setBluetoothScoOn(true);
                    audioManager.startBluetoothSco();
                    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);*//*

                }
            }*/
/*
               if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                   BluetoothDevice  device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                   Log.e("BlueToothTestActivity",device.toString());
                   switch (device.getBondState()){
                       case BluetoothDevice.BOND_BONDING://正在配对
                           Log.d("BlueToothTestActivity", "正在配对......");
//                           onRegisterBltReceiver.onBltIng(device);
                           break;
                       case BluetoothDevice.BOND_BONDED://配对结束
                           Log.d("BlueToothTestActivity", "完成配对");
//                           onRegisterBltReceiver.onBltEnd(device);
                           break;
                       case BluetoothDevice.BOND_NONE://取消配对/未配对
                           Log.d("BlueToothTestActivity", "取消配对");
//                           onRegisterBltReceiver.onBltNone(device);
                       default:
                           break;
                   }
               }
*/

        }
    };

//    private void closesocket() {
//        YCHSInstance.resetInstance();
//        YCHSWebSocketAPI.getApp().closeSocket();
//    }

    private void updateUser(List<MeetingUser> users) {
        Log.d(TAG, "updateUser......");
        if (timer != null) {
            timer.cancel();
            timer = null;
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
        }
        List<MeetingUser> userList = YCHSConferenceClient.getInstance().getUserList();
        userList.clear();
        userList.addAll(users);
        attendanceNm = userList.size();
        for (MeetingUser user : userList) {
            if (YCHSInstance.getInstance().getLoginUser().getUSER_CODE().equals(user.getUserSN())) {
                meetingUser = user;
                Logger.e(" updateUser meetingUser " + meetingUser);
                YCHSConferenceClient.getInstance().setMCURole(meetingUser.getRole());
                initIconView();
                break;
            }
        }
        Collections.sort(userList, new Comparator<MeetingUser>() {
            public int compare(MeetingUser arg0, MeetingUser arg1) {
                return arg0.getRole().compareTo(arg1.getRole());
            }
        });
        myAdapter.notifyDataSetChanged();
        /*
         * chatUseradapter.clear(); chatUseradapter.add("所有人");
         */
        //20171123 新增黑屏修改
//        meetingScreenGrid.getContainer().setVisibility(View.GONE);
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        if (YCHSConferenceClient.getInstance().getRemoteStreams().size() > 0) {
            RemoteStream rs = YCHSConferenceClient.getInstance()
                    .getRemoteStreamsById(
                            YCHSConferenceClient.getInstance()
                                    .getJoinResponse().getCurrShareStreamId());
            if (rs == null) {
                Log.d(TAG, "rs= null....");
                //20171123加入openbigVideo 屏幕最大化标志位判定
                if (!isShareDesktop) {
                    dissLocalCameraView();
                    meetingScreenGrid.getContainer()
                            .setVisibility(View.VISIBLE);
                    fixResolution(vm, width, height);
                    //默认不可以显示mix流
                    if (isVideoOpen) {
                        conferenceStreamView.playRemoteStreamId("", checksound);
                        Log.e("GetTime", "isVideoOpen true");
                    }
                    conferenceStreamView.getContainer().setVisibility(View.VISIBLE);

                    localVideoDescView2.setVisibility(View.VISIBLE);

                    if (isVideoOpen) {
                        meetingScreenGrid.updateScreenGrid(YCHSConferenceClient
                                .getInstance().getConferenceClient(), userList);
                    }

                }
            } else {
                Log.d(TAG, "rs != null....");
                localVideoDescView2.setVisibility(View.VISIBLE);
                meetingScreenGrid.getContainer().setVisibility(View.GONE);
                normalResolution(vm, width, height);
                conferenceStreamView.playRemoteStream(rs);
            }

        } else {
            conferenceStreamView.stop();
        }
    }

    public void onEventMainThread(AttacheFileEvent event) {
        Toast.makeText(ConferenceRoomUI.this, "附件列表更新！", Toast.LENGTH_LONG).show();
        Log.e(TAG, "AttacheFileEvent:" + event);
        updateAttacheFiles();
    }

    public void onEventMainThread(ExitMeetingEvent event) {
        Log.e(TAG, "ExitMeetingEvent:" + event);
        if (YCHSInstance.getInstance().getLoginUser().getUSER_CODE().equals(event.getUserCode())) {
            promptDialog(event.getMessage(), new PromptListener() {
                @Override
                public void callBack() {
                    exit();
                }
            });
        } else {
            YCHSConferenceClient.getInstance().getMeetingUserListAlone();
            // updateUser();
        }
    }

    public void onEventMainThread(GetMeetingUserListEvent event) {
        updateUser(event.getUserList());
    }

    public void onEventMainThread(ChatMessageEvent event) {
        Log.d(TAG, "ChatMessageEvent: ");
//        if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        if (ConfigUtil.getInstance().getMsg()) {
            Toast.makeText(ConferenceRoomUI.this, "音视频互动：有新消息!", Toast.LENGTH_SHORT).show();
        }
        Log.e(TAG, "ChatMessageEvent:" + event.toString());
//        ChatMessage chatMessage = YCHSConferenceClient.getApp().getChatMessages().get(YCHSConferenceClient.getApp().getChatMessages().size() - 1);
//        if (chatMessage.getUserCode().equalsIgnoreCase(event.getChatMessage().getUserCode())
//                &&chatMessage.getMessage().equalsIgnoreCase(event.getChatMessage().getMessage())) {
//            return;
//        }
        YCHSConferenceClient.getInstance().addChatMessage(event.getChatMessage());
        mConferenceChatView.refresh();
    }

    public void onEventMainThread(ShareVideoEvent event) {
        isExitShareVideo = true;
        Log.e(TAG, "ChatMessageEvent:" + event);
        content_frame.setBackgroundColor(getResources().getColor(R.color.gray5));
        YCHSConferenceClient.getInstance().getJoinResponse()
                .setCurrShareStreamId(event.getShareVideo().getStreamId());
//		isVideoOpen = true;
        normalResolution(vm, width, height);
        viewPager.setCurrentItem(1, false);
        zoomStreamView.playRemoteStreamId(event.getShareVideo().getStreamId());
        //YCHSConferenceClient.getApp().getMeetingUserListAlone();
//		meetingLocalStreamView.playLocalStream(localStream);
    }

    public void onEventMainThread(StopShareEvent event) {
        if (zoomStreamView != null) {
            zoomStreamView.stopRemoteStream();
        }
        viewPager.setCurrentItem(0, false);
        content_frame.setBackgroundColor(getResources().getColor(R.color.default_person_bg2));
        YCHSConferenceClient.getInstance().getJoinResponse()
                .setCurrShareStreamId(null);
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();

    }

    public void onEventMainThread(JoinEvent event) {
        Log.e(TAG, "JoinEvent:" + event);
        //非抢修互动可以显示视频
//        if (!"1".equals(YCHSConferenceClient.getApp().getMeeting_type())) {
        isVideoOpen = true;
//        }
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();
        JoinResponse jr = event.getJoinResponse();
        if (jr != null) {
            YCHSConferenceClient.getInstance().setJoinResponse(jr);
        }
        if (jr.getCurrShareStreamId() != null) {
            zoomStreamView.playRemoteStreamId(jr.getCurrShareStreamId());
            viewPager.setCurrentItem(1, false);
        }
        // roomHandler.sendEmptyMessage(MSG_PUBLISH);
        // if(event.getJoinResponse().getUserCode().equals(YCHSInstance.getApp().getLoginUser().getUSER_CODE())){
        publishLocalStream(videoRate, null);
        // }

        audioStatus = jr.getAudioStatus();
        videoStatus = jr.getVideoStatus();
        audioForbid = jr.getAudioForbid();
        videoForbid = jr.getVideoForbid();
        YCHSInstance.getInstance().setMode(jr.getMode());

        Log.d(TAG, "onEventMainThread: ");

        if (jr.getMuted() == 1) {
            speak_img.setImageResource(R.drawable.forbid_talk);
            IsNomute = false;
        } else if (jr.getMuted() == 2) {
            speak_img.setImageResource(R.drawable.allow_talk);
            IsNomute = true;
        }
    }

    public void onEventMainThread(OnStreamRemoveEvent event) {
        //如果流是本地的视频流 且不是退出就重新连接下 且不是听众
        Log.d(TAG, "onEventMainThread: OnStreamRemoveEvent");
        if (localStream.getId().equals(event.getStreamId()) && !isExit && !"4".equals(YCHSConferenceClient.getInstance().getMCURole())) {
            Log.d(TAG, "republish: OnStreamRemoveEvent");
            SwitchToMainThread.getInstance().postDelayed(new Runnable() { //当时接收到OnStreamRemove事件时，延迟10s发布流，便可以重新看到流。
                @Override
                public void run() {
                    publishLocalStream(videoRate, null);
                }
            }, 10000);
        }
    }

    public void onEventMainThread(CloseMixStreamEvent event) {
        String userCode = YCHSInstance.getInstance().getLoginUser().getUSER_CODE();
        if (conferenceStreamView != null && "close".equals(event.getAction()) && event.getUserCode().equals(userCode)) {
            conferenceStreamView.stopRemoteStream();
            isVideoOpen = false;
            if (meetingScreenGrid != null) {
                meetingScreenGrid.restore();
            }
        } else if (conferenceStreamView != null && "open".equals(event.getAction()) && event.getUserCode().equals(userCode)) {
            isVideoOpen = true;
            YCHSConferenceClient.getInstance().getMeetingUserListAlone();
        }
    }

    public void onEventMainThread(ChangeUserRoleEvent event) {
        Log.e(TAG, "ChangeUserRoleEvent:" + event);
        YCHSConferenceClient.getInstance().setMCURole(event.getStatus());
        if (YCHSInstance.getInstance().getLoginUser() == null) {
            return;
        }
        String userCodeString = YCHSInstance.getInstance().getLoginUser()
                .getUSER_CODE();
        String releaseRegionString = event.getReplaceRegion();
        if (userCodeString.equals(event.getUserCode())) {
            if ("4".equals(event.getStatus())) {
                isEventUserListener = 0;
                localStream.disableVideo();
                isOpenCameraOrNot = false;
                localStream.disableAudio();
                unPublishLocalStream2();
                // 将自己的视频从设备移出 后向 需要被加入视频的人发送changeUserRole
                if (String.valueOf(event.getAddVideoUser()) != null) {
                    sendChangeUserSocket(
                            YCHSWebSocketAPI.getInstance().TYPE_ChangeUserRole,
                            event.getAddVideoUser(), "3", null,
                            event.getReplaceRegion());// 3.表示参会人员
                }
            } else {
                if (isEventUserListener == 0) {
                    isEventUserListener = 1;
                    if (localStream != null) {
                        localStream.enableVideo();
                        isOpenCameraOrNot = true;
                        localStream.enableAudio();
                        publishLocalStream2(videoRate, releaseRegionString);
                    } else {
                        publishLocalStream(videoRate, releaseRegionString);
                    }
                }
            }
            // 当更改了用户角色后要给主持人和助手重新排序
            sortHostOrAssistant(event.getStatus());
        }
        // sleep一下是因为在手机端修改用户角色后名字对应问题，只有sleep后取到的结果才正确
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();
    }

    /**
     * 当更改了用户角色后要给主持人和助手重新排序
     */
    private void sortHostOrAssistant(String roleStatus) {

        try {
            if (localStream != null) {
                String streamId = localStream.getId();
                RemoteStream remoteStream = null;
                List<RemoteStream> streams = YCHSConferenceClient.getInstance()
                        .getRemoteStreams();
                for (RemoteStream stream : streams) {
                    if (streamId.equals(stream.getId())) {
                        remoteStream = stream;
                        break;
                    }
                }
                if ("1".equals(roleStatus)) {
                    YCHSConferenceClient.getInstance().setRegion(remoteStream,
                            "1", null);
                }
                if ("2".equals(roleStatus)) {
                    YCHSConferenceClient.getInstance().setRegion(remoteStream,
                            "2", null);
                }

            }

        } catch (Exception e) {
//            meetingLocalStreamView.stop();
            e.printStackTrace();
        }

    }

    public void onEventMainThread(ApplyForSpeakerEvent event) {
        Log.e(TAG, "ApplyForSpeakerEvent:" + event);
        applySpeakerList.add(event.getUserCode());
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();
    }

    public void onEventMainThread(AddVideoStreamEvent event) {
        Log.e(TAG, "AddVideoStreamEvent:" + event);
        if (event.getUserCode().equals(YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            openVideo();
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    public void onEventMainThread(CloseVideoStreamEvent event) {
        Log.e(TAG, "CloseVideoStreamEvent:" + event);
        if (event.getUserCode().equals(YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            closeVideo();
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    public void onEventMainThread(AddAudioStreamEvent event) {
        Log.e(TAG, "AddAudioStreamEvent:" + event);
        if (event.getUserCode().equals(YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            openAudio();
            RefreshView("addAudioStream");
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    public void onEventMainThread(CloseAudioStreamEvent event) {
        Log.e(TAG, "AddAudioStreamEvent:" + event);
        if (event.getUserCode().equals(YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            RefreshView("deleteAudioStream");
            closeAudio();
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    public void onEventMainThread(EndMeetingEvent event) {
        Log.e(TAG, "EndMeetingEvent:" + event);
        if (event.getResultCode() == 0 ||
                event.getResultCode() == 1 ||
                event.getResultCode() == 2) {
//            backPressed();
//            Toast toast = ToastUtil.showGravity(this, event.getMessage(), Gravity.CENTER);
//            ToastUtil.showMyToast(toast, 6 * 1000);
            finish();
            ToastUtil.showLong(MyApp.getApp(), "会议已结束");
        } else {
            if (event.getErrorMessage() != null) {
                ToastUtil.showLong(MyApp.getApp(), event.getErrorMessage());
            }
        }
    }

    public void onEventMainThread(ChangeHostAssistListEvent event) {
        Log.e(TAG, "ChangeHostAssistListEvent:" + event);
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();
    }

    public void onEventMainThread(ForbidTalkEvent event) {
        Log.e(TAG, "ForbidTalkEvent:" + event);
        if (event.getUserCode().equals(
                YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            promptDialog("您已经被禁止聊天！", new PromptListener() {

                @Override
                public void callBack() {
                    // TODO Auto-generated method stub
//                    YCHSWebSocketAPI.getApp().getMeetingUserListAlone(
//                            YCHSConferenceClient.getApp().getMeetingId());
                }
            });
            mConferenceChatView.setForbidTalk();
        } else {
            YCHSWebSocketAPI.getInstance().getMeetingUserListAlone(
                    YCHSConferenceClient.getInstance().getMeetingId());
        }
    }

    public void onEventMainThread(EditAliasNameEvent event) {
        Log.e(TAG, "EditAliasNameEvent:" + event);
        if ("0".equals(event.getResultCode())) {
            if (meetingScreenGrid != null) {
                meetingScreenGrid.updateAliasName(event.getUserCode(), event.getAliasName());
            }
        }
    }

    public void onEventMainThread(ShareDeskTopEvent event) {
        Log.e(TAG, "ShareDeskTopEvent:.....");
        if (event.getFlag() == 1) {
//            content_frame.setBackgroundColor(getResources().getColor(R.color.gray5));
//            meetingScreenGrid.getContainer().setVisibility(View.GONE);
//            viewPager.setCurrentItem(1, false);
//            zoomStreamView.playRemoteStream(event.getRemoteStream(), checksound);
//            normalResolution(vm, width, height);

            String streamId = event.getRemoteStream().getId();
            List<RemoteStream> streams = YCHSConferenceClient.getInstance().getConferenceClient().getRemoteStreams();
            for (RemoteStream stream : streams) {
                if (stream.getId().equals(streamId)) {
                    Log.d(TAG, "onEventMainThread: " + streamId);
                    showZoomVideo(stream, "");
                    break;
                }
            }

//            conferenceStreamView.playRemoteStream(event.getRemoteStream());
//            isShareDesktop = true;
//            isExitShareVideo = true;
//			meetingLocalStreamView.playLocalStream(localStream);
        } else {
//            meetingScreenGrid.getContainer().setVisibility(View.VISIBLE);
//            fixResolution(vm, width, height);
////			conferenceStreamView.playRemoteStream(null);
////			conferenceStreamView.stopNotSetNull();
////			zoomStreamView.stopNotSetNull();
//            viewPager.setCurrentItem(1, false);

            dismissZoomVideo();

//            isShareDesktop = false;
//            isExitShareVideo = true;
//			meetingLocalStreamView.stop();
        }
        YCHSConferenceClient.getInstance().getMeetingUserListAlone();
    }


    private CustomDialog zoomDialog;
    private volatile boolean subscribeSuccess = false;//true 订阅视频成功 ， false 订阅视频失败

    /**
     * 显示大视频
     *
     * @param stream
     */
    private void showZoomVideo(final RemoteStream stream, String userCode) {
        if (zoomDialog != null && zoomDialog.isShowing()) {
            return;
        }
//        if (!isStartWithZoomVideo) {
//            //打开大视频时暂停混合流，减小流量消耗
//            pauseMixStreamVideo();
//        }

        Log.d(TAG, "showZoomVideo: userCode====>" + userCode);

        NewZoomDialogManger manger = new NewZoomDialogManger(
                ConferenceRoomUI.this, new NewZoomDialogManger.OnZoomListener() {
            @Override
            public void onStartSubscribe(CustomSurfaceRenderer zoomSurfaceRenderer,
                                         Stream.VideoRendererInterface zoomStreamRenderer,
                                         NewZoomDialogManger manger1) {
                SwitchToMainThread.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog = ProgressDialog.show(ConferenceRoomUI.this, "加载中...", "正在加载大视频，请稍后...", false, true);
                    }
                });
                Log.d(TAG, "onStartSubscribe: ");
                subscribeZoomStream(stream, zoomSurfaceRenderer, zoomStreamRenderer, manger1);
            }

            @Override
            public void onDismiss(CustomSurfaceRenderer zoomSurfaceRenderer, Stream.VideoRendererInterface zoomStreamRenderer) {
                unSubscribeZoomStream(stream, zoomSurfaceRenderer, zoomStreamRenderer);
                SwitchToMainThread.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                    }
                });
//                if (!isStartWithZoomVideo) {
//                    playMixStreamVideo();
//                } else {
//                    progressDialog = ProgressDialog.show(ConferenceRoomUI.this, "加载中...", "正在获取视频", false, true);
//                    resubscribeMixedStream(true);
//                }
            }

        });

        zoomDialog = new CustomDialog()
                .setView(R.layout.dialog_zoom_view)
                .setCanceledOnTouchOutside(false)
                .builder(ConferenceRoomUI.this, R.style.comment_full_screen_dialog)
                .create()
                .viewManager(manger);
        zoomDialog.show();

    }

    private static final long SHOW_ZOOM_VIDEO_TIME_OUT = 10 * 1000; //显示大视频超时时间

    /**
     * 订阅放大视频流
     *
     * @param stream
     * @param zoomSurfaceRenderer
     * @param zoomStreamRenderer
     */
    private void subscribeZoomStream(final RemoteStream stream,
                                     final CustomSurfaceRenderer zoomSurfaceRenderer,
                                     final Stream.VideoRendererInterface zoomStreamRenderer,
                                     final NewZoomDialogManger manger1) {
        SubscribeOptions option = new SubscribeOptions();
        option.setVideoCodec("0".equals(ConfigUtil.getInstance().getCompressType()) ? VideoCodec.VP8 : VideoCodec.H264);
        YCHSConferenceClient.getInstance().getConferenceClient().subscribe(
                stream, option, new ActionCallback<RemoteStream>() {
                    @Override
                    public void onSuccess(RemoteStream remoteStream) {
                        SwitchToMainThread.getInstance().post(new Runnable() {
                            @Override
                            public void run() {
                                dismissDialog();
                            }
                        });
                        Log.d(TAG, "subscribeZoomStream onSuccess: ");
                        subscribeSuccess = true;
                        try {
                            remoteStream.attach(zoomStreamRenderer);
                            Log.d(TAG, "onSuccess: remoteStream");

                        } catch (WoogeenIllegalArgumentException e) {
                            Log.e(TAG, "onSuccess: " + e.getMessage());
                            zoomSurfaceRenderer.reset(zoomStreamRenderer);
                        }

//                        SwitchToIOThread.getApp().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (manger1.getPreReceived() == 0) {
//                                    SwitchToMainThread.getApp().post(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            ToastUtil.showLong(ConferenceApp.getApp(), "当前网络不稳定");
//                                            dismissZoomVideo();
//                                        }
//                                    });
//                                }
//                            }
//                        }, SHOW_ZOOM_VIDEO_TIME_OUT);
                    }

                    @Override
                    public void onFailure(WoogeenException e) {
                        Log.e(TAG, "subscribeZoomStream onFailure: " + e.getMessage());
                        subscribeSuccess = false;
                        cleanZoomStream(stream, zoomSurfaceRenderer, zoomStreamRenderer);
                        SwitchToMainThread.getInstance().post(new Runnable() {
                            @Override
                            public void run() {
                                dismissDialog();
                                ToastUtil.showLong(ConferenceApp.getApp(), "视频显示失败");
                            }
                        });
                    }
                });
    }

    /**
     * 取消订阅放大视频流
     *
     * @param stream
     */
    private void unSubscribeZoomStream(final RemoteStream stream,
                                       final CustomSurfaceRenderer zoomSurfaceRenderer,
                                       final Stream.VideoRendererInterface zoomStreamRenderer) {
        if (subscribeSuccess) {
            YCHSConferenceClient.getInstance().getConferenceClient().unsubscribe(stream, new ActionCallback() {
                @Override
                public void onSuccess(Object o) {
                    Log.d(TAG, "unSubscribeZoomStream onSuccess: ");
                    cleanZoomStream(stream, zoomSurfaceRenderer, zoomStreamRenderer);
                    SwitchToMainThread.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showShort(ConferenceApp.getApp(), "退出大视频");
                        }
                    });
                }

                @Override
                public void onFailure(WoogeenException e) {
                    Log.e(TAG, "unSubscribeZoomStream onFailure: " + e.getMessage());
                    cleanZoomStream(stream, zoomSurfaceRenderer, zoomStreamRenderer);
                    SwitchToMainThread.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showShort(ConferenceApp.getApp(), "大视频退出失败");
                        }
                    });
                }
            });
        }
        Log.d(TAG, "unSubscribeZoomStream: end");
    }

    /**
     * 释放大视频资源
     *
     * @param stream
     * @param zoomSurfaceRenderer
     * @param zoomStreamRenderer
     */
    private void cleanZoomStream(RemoteStream stream,
                                 CustomSurfaceRenderer zoomSurfaceRenderer,
                                 Stream.VideoRendererInterface zoomStreamRenderer) {

        if (stream != null) {
            stream.detach();
        }
        if (zoomStreamRenderer != null) {
            zoomStreamRenderer.cleanFrame();
        }
        if (zoomSurfaceRenderer != null) {
            zoomSurfaceRenderer.cancel();
            zoomSurfaceRenderer.dispose();
        }


        zoomStreamRenderer = null;
        zoomSurfaceRenderer = null;

    }

    /**
     * 关闭dialog
     */
    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * 关闭放大视频
     */
    private void dismissZoomVideo() {
        if (zoomDialog != null && zoomDialog.isShowing()) {
            zoomDialog.dismiss();
            zoomDialog = null;
        }
    }

    public void onEventMainThread(AllowTalkEvent event) {
        Log.e(TAG, "AllowTalkEvent:" + event);
        if (event.getUserCode().equals(
                YCHSInstance.getInstance().getLoginUser().getUSER_CODE())) {
            promptDialog("您可以自由聊天！", new PromptListener() {

                @Override
                public void callBack() {
                    // TODO Auto-generated method stub
//                    YCHSWebSocketAPI.getApp().getMeetingUserListAlone(
//                            YCHSConferenceClient.getApp().getMeetingId());
                }
            });

            mConferenceChatView.setAllowTalk();
        } else {
            YCHSWebSocketAPI.getInstance().getMeetingUserListAlone(
                    YCHSConferenceClient.getInstance().getMeetingId());
        }
    }

    public void onEventMainThread(TempRoomEvent event) {
        Log.e(TAG, "TempRoomEvent: mode ==> " + event.getMode());
        if (event.getResultCode() == 0) {
            if (event.getMode() == 1
                    && !YCHSConferenceClient.getInstance()
                    .hasConferenceControlPermission()) {
//                closeAudio();
                Log.d(TAG, "TempRoomEvent: close");
                localStream.disableAudio();
                audio_img.setBackgroundResource(R.drawable.u103);
                checkMic = false;
            } else {
//                openAudio();
                Log.d(TAG, "TempRoomEvent: open");
                localStream.enableAudio();
                audio_img.setBackgroundResource(R.drawable.u102);
                checkMic = true;
            }
            YCHSInstance.getInstance().setMode(event.getMode());
        }
    }

    public void onEventMainThread(DisableAudioEvent event) {
        Log.e(TAG, "DisableAudioEvent:" + event);
        if (event.getResultCode() == 0) {
            //add 2018 0813  此判断不合理，删去
//            if ("all".equals(event.getStreamId())
//                    || meetingUser.getStreamId().equals(event.getStreamId())) {
            if ((!"1".equals(meetingUser.getRole()) && !"2".equals(meetingUser.getRole()) && "all".equals(event.getStreamId()))) {
                checkMic = false;
                closeAudio();
                //RefreshView();
            }
            // }
        }
    }

    public void onEventMainThread(EnableAudioEvent event) {
        Log.e(TAG, "EnableAudioEvent:" + event);
        if (event.getResultCode() == 0) {
            //add 2018 0813  此判断不合理，删去
//            if ("all".equals(event.getStreamId())
//                    || meetingUser.getStreamId().equals(event.getStreamId())) {
            if ((!"1".equals(meetingUser.getRole()) && !"2".equals(meetingUser.getRole()) && "all".equals(event.getStreamId()))) {
                checkMic = true;
                openAudio();

                // RefreshView();
                // }
            }
        }
    }

    public void onEventMainThread(StartRecordEvent event) {
        if (event.getResultCode() == 0 && event.getFile() != null) {
            YCHSInstance.getInstance().setRecorderId(
                    event.getFile().getRecorderId());
        }
    }

    public void onEventMainThread(ExitConferenceEvent event) {
        Log.d(TAG, "ExitConferenceEvent: start");
        Log.d(TAG, "ExitConferenceEvent: IsOut= " + IsOut);
        if (!IsOut) {
//            YCHSWebSocketAPI.getApp().closeSocket();
            Log.d(TAG, "onEventMainThread: finish");
            ToastUtil.showLong(MyApp.getApp(), "断开连接，离开会议");
            finish();
            IsOut = false;
        }
    }

    private void unPublishLocalStream() {
//        if (localStream != null) {
//            YCHSConferenceClient.getApp().unpublish(localStream,
//                    new ActionCallback<Void>() {
//                        @Override
//                        public void onSuccess(Void result) {
//                             finish();
//                        }
//
//                        @Override
//                        public void onFailure(WoogeenException e) {
//                           Logger.e("unPublishLocalStream "+e.getMessage());
//                        }
//                    });
//        }
        leave();
    }

    private void leave() {
        HDMsgUtils.stop();
        YCHSConferenceClient.getInstance().leave(new ActionCallback<Void>() {
            @Override
            public void onFailure(WoogeenException arg0) {
                finish();
            }

            @Override
            public void onSuccess(Void arg0) {
                exitMeeting();
                finish();
            }
        });
    }

    private void unPublishLocalStream2() {
        if (localStream != null) {
            YCHSConferenceClient.getInstance().unpublish(localStream,
                    new ActionCallback<Void>() {
                        @Override
                        public void onSuccess(Void result) {

                        }

                        @Override
                        public void onFailure(WoogeenException e) {
                            Log.d(TAG, e.getMessage());
                        }
                    });
        }
    }

    private void exitMeeting() {
        YCHSWebSocketAPI.getInstance().exitMeeting(
                YCHSConferenceClient.getInstance().getMeetingId());
        YCHSConferenceClient.getInstance().clear();
        YCHSWebSocketAPI.getInstance().closeSocket();
    }

    private void publishLocalStream(int rate, final String releaseRegion) {
        Log.d(TAG, "publishLocalStream "
                + YCHSConferenceClient.getInstance().getMCURole());
        if (!"4".equals(YCHSConferenceClient.getInstance().getMCURole())) {
            try {
                LocalCameraStreamParameters msp = new LocalCameraStreamParameters(
                        true, true);
                PublishOptions option = new PublishOptions();
                // msp.setCamera(CameraType.FRONT);
                msp.setDisplayOrientation(ConferenceRoomUI.this);

                if (rate == 3) {
                    String resolution = ConfigUtil.getInstance()
                            .getResolution();
                    String resolutionstr = getResolution(resolution);
                    Log.e("GetTime", resolutionstr);
                    if (!TextUtils.isEmpty(resolutionstr)) {
                        switch (Integer.parseInt(resolutionstr.split("x")[0])) {
                            case 720:
                                msp.setResolution(1280, 720);
                                maximumVideoBandwidth = 600;
                                option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                                option.setMaximumAudioBandwidth(50);
                                break;
                            case 640:
                                msp.setResolution(640, 480);
                                // msp.setResolution(640, 360);
                                maximumVideoBandwidth = 300;
                                option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                                option.setMaximumAudioBandwidth(50);
                                netSpeed = 90;
                                break;
                            case 320:
                                msp.setResolution(320, 240);
                                // msp.setResolution(750, 420);
                                maximumVideoBandwidth = 200;
                                option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                                option.setMaximumAudioBandwidth(50);
                                break;
                            case 1920:
                                msp.setResolution(1920, 1080);
                                maximumVideoBandwidth = 2000;
                                option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                                option.setMaximumAudioBandwidth(50);
                                break;
                            default:
                                msp.setResolution(640, 480);
                                // msp.setResolution(1024, 576);
                                maximumVideoBandwidth = 300;
                                option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                                option.setMaximumAudioBandwidth(50);
                                break;
                        }
                    }
                } else if (rate == 2) {
                    msp.setResolution(640, 480);
                    // msp.setResolution(640, 360);
                    maximumVideoBandwidth = 600;
                    option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                    option.setMaximumAudioBandwidth(100);

                    netSpeed = 90;
                } else if (rate == 1) {
                    msp.setResolution(180, 120);
                    // msp.setResolution(1280, 720);
                    maximumVideoBandwidth = 168;
                    option.setMaximumVideoBandwidth(maximumVideoBandwidth);
                    option.setMaximumAudioBandwidth(28);
                    netSpeed = 35;
                } else {
                    Toast.makeText(ConferenceRoomUI.this, "已经是最低分辨率！", Toast.LENGTH_SHORT).show();
                }
                option.setVideoCodec("0".equals(ConfigUtil.getInstance().getCompressType()) ? VideoCodec.VP8 : VideoCodec.H264);

                if (localStream == null) {
                    localStream = new LocalCameraStream(msp);
                }
                if (meetingUser != null) {
                    if ("deleteVideoStream"
                            .equals(meetingUser.getVideoStatus())) {
                        localStream.disableVideo();
                        isOpenCameraOrNot = false;
                    }
                    if ("deleteAudioStream"
                            .equals(meetingUser.getAudioStatus())) {
                        localStream.disableAudio();
                    }
                }
                realPublishStream(localStream, option, releaseRegion);
            } catch (Exception e) {
                Log.e(TAG, "publishLocalStream: " + e.getMessage());
            }
        } else {
            isEventUserListener = 0;
        }
    }

    private void realPublishStream(final LocalCameraStream localStream, PublishOptions options,
                                   final String releaseRegion) {

        YCHSConferenceClient.getInstance().publish(localStream, options,
                new ActionCallback<Void>() {
                    @Override
                    public void onSuccess(final Void result) {

                        if (releaseRegion != null) {
                            String streamId = localStream.getId();
                            RemoteStream remoteStream = null;
                            // remoteStream =
                            // YCHSConferenceClient.getApp().getRemoteStreamsById(streamId);
                            List<RemoteStream> streams = YCHSConferenceClient
                                    .getInstance().getRemoteStreams();
                            for (RemoteStream stream : streams) {
                                if (streamId.equals(stream.getId())) {
                                    remoteStream = stream;
                                    break;
                                }
                            }
                            YCHSConferenceClient.getInstance()
                                    .setRegion(remoteStream,
                                            releaseRegion, null);
                        }
                        localStreamAudioStatus(audioStatus);
                        localStreamVideoStatus(videoStatus);
                    }

                    @Override
                    public void onFailure(final WoogeenException e) {
                        Log.e(TAG, " realPublishStream onFailure: " + e.getMessage());
                    }

                });
    }


    private String getResolution(String str) {
        String string = "";
        if ("高清(720)".equals(str)) {
            string = "1280x720";
            netSpeed = 180;
        } else if ("标清(640)".equals(str)) {
            string = "640x480";
            netSpeed = 90;
        } else if ("流畅(320)".equals(str)) {
            string = "320x240";
            netSpeed = 35;
        }
        return string;
    }

    private void publishLocalStream2(int rate, final String releaseRegion) {
        Log.e("publishLocalStream", "publishLocalStream "
                + YCHSConferenceClient.getInstance().getMCURole());
        try {
            PublishOptions option = new PublishOptions();
            // msp.setCamera(CameraType.FRONT);

            maximumVideoBandwidth = 168;
            option.setMaximumVideoBandwidth(maximumVideoBandwidth);
            option.setMaximumAudioBandwidth(28);
            option.setVideoCodec("0".equals(ConfigUtil.getInstance().getCompressType()) ? VideoCodec.VP8 : VideoCodec.H264);

            if (meetingUser != null) {
                if ("deleteVideoStream".equals(meetingUser.getVideoStatus())) {
                    localStream.disableVideo();
                    isOpenCameraOrNot = false;
                }
                if ("deleteAudioStream".equals(meetingUser.getAudioStatus())) {
                    localStream.disableAudio();
                }
            }

            // meetingLocalStreamView.playLocalStream(localStream);
            YCHSConferenceClient.getInstance().publish(localStream, option,
                    new ActionCallback<Void>() {
                        @Override
                        public void onSuccess(final Void result) {
                            if (releaseRegion != null) {
                                String streamId = localStream.getId();
                                // RemoteStream remoteStream =
                                // YCHSConferenceClient.getApp().getRemoteStreamsById(streamId);;
                                RemoteStream remoteStream = null;
                                List<RemoteStream> streams = YCHSConferenceClient
                                        .getInstance().getRemoteStreams();
                                for (RemoteStream stream : streams) {
                                    if (streamId.equals(stream.getId())) {
                                        remoteStream = stream;
                                        break;
                                    }
                                }
                                YCHSConferenceClient.getInstance().setRegion(
                                        remoteStream, releaseRegion, null);
                            }
                            YCHSConferenceClient.getInstance()
                                    .getMeetingUserListAlone();
                        }

                        @Override
                        public void onFailure(final WoogeenException e) {
                            e.printStackTrace();
                        }

                    });
        } catch (Exception e) {
//            meetingLocalStreamView.stop();
            e.printStackTrace();
        }
    }

    private void updateAttacheFiles() {
        String meetingId = getIntent().getStringExtra(MEETING_ID);
        YCHShttpAPI.GetMeetingFileList(ConferenceRoomUI.this, meetingId,
                new StringCallback() {

                    @Override
                    public void onResponse(String response) {
                        // TODO Auto-generated method stub
                        Log.e("file", response.toString());
                        OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                        if ("0".equals(onResponse.getResultCode())) {
                            fileList = onResponse.getFileList();
                            fileAdapter.notifyDataSetChanged();
                            Log.e("file", fileList.toString());
                        } else if ("-2".equals(onResponse.getResultCode())) {
                            Intent intent = new Intent(ConferenceRoomUI.this, TimeOutActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else {
//                            if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                                ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                                Platform.getCurrent().stop(getApplicationContext());
//                                ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                                return;
//                            }
                            showErrorWithStatus("附件获取失败！");
                        }
                    }

                    @Override
                    public void onError(Call call, int statusCode, Exception e) {
                        // TODO Auto-generated method stub
                        // showErrorWithStatus("附件获取失败！");
                    }
                });
    }

    @Override
    protected void initViews() {


//        iv_menu_room = (ImageView) findViewById(R.id.iv_menu_room);
//        iv_menu_room.setOnClickListener(this);
        // sp_toperson = (Spinner) findViewById(R.id.sp_toperson);
        lv_lvpersion = (ListView) findViewById(R.id.lv_lvpersion);
        lv_lvfile = (ListView) findViewById(R.id.lv_lvfile);
        ll_fileLayout = (LinearLayout) findViewById(R.id.ll_filelayout);

        tv_tabusers = (TextView) findViewById(R.id.tv_tabusers);
        tv_tabfiles = (TextView) findViewById(R.id.tv_tabfiles);

        ll_tackphoto = (LinearLayout) findViewById(R.id.ll_tackphoto);
        ll_gallery = (LinearLayout) findViewById(R.id.ll_gallery);
        // lv_chart = (ListView) findViewById(R.id.lv_chart);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout2);

        iv_open = (ImageView) findViewById(R.id.iv_open);
        iv_close = (ImageView) findViewById(R.id.iv_close);
        tx_open = (TextView) findViewById(R.id.tx_open);
//        room_name = (TextView) findViewById(R.id.room_name);

        content_frame = findViewById(R.id.content_frame);
        id_drawerlayout2 = findViewById(R.id.id_drawerlayout2);
        content_frame.setOnClickListener(this);
//        toolbar = findViewById(R.id.room_toolbar);
        // chat_input = (EditText)findViewById(R.id.chat_input);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        pageViews = new ArrayList<>();
        LayoutInflater inflater = getLayoutInflater();
        conferenceView = inflater.inflate(R.layout.view_conference, null);
        zoomView = inflater.inflate(R.layout.view_zoom, null);
        zoomView.findViewById(R.id.zoomView).setOnClickListener(this);
        mConferenceChatView = new ConferenceChatView((LinearLayout) conferenceView.findViewById(R.id.chat_container), this);

        upView = (ImageView) zoomView.findViewById(R.id.upView);
        downView = (ImageView) zoomView.findViewById(R.id.downView);
        rightView = (ImageView) zoomView.findViewById(R.id.rightView);
        leftView = (ImageView) zoomView.findViewById(R.id.leftView);
        zoomInView = (ImageView) zoomView.findViewById(R.id.zoomInView);
        zoomOutView = (ImageView) zoomView.findViewById(R.id.zoomOutView);
        controlDeviceView = zoomView.findViewById(R.id.controlDeviceView);


        // 退出
        btn_09 = (View) conferenceView.findViewById(R.id.btn_09);
        //关闭麦克风
        btn_03 = (View) conferenceView.findViewById(R.id.btn_03);
        //切换摄像头
        btn_01 = (View) conferenceView.findViewById(R.id.btn_01);
        //开关摄像头
        btn_06 = (View) conferenceView.findViewById(R.id.btn_06);
        //全部静音
        btn_07 = (View) conferenceView.findViewById(R.id.btn_07);
        speakerImg = (ImageView) conferenceView.findViewById(R.id.spkeaker_img);
        audio_img = (ImageView) conferenceView.findViewById(R.id.audio_img);
        audio_img.setBackgroundResource(R.drawable.u102);
        //设置禁言
        btn_10 = (View) conferenceView.findViewById(R.id.btn_10);
        speak_img = (ImageView) conferenceView.findViewById(R.id.speak_img);
        video_img = (ImageView) conferenceView.findViewById(R.id.video_img);
        iv_back = (ImageView) conferenceView.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        //聊天模块
        chat_view = (LinearLayout) conferenceView.findViewById(R.id.chat_view);
        chatback = (TextView) conferenceView.findViewById(R.id.chat_back);
        //添加文件
        addfile = (ImageView) conferenceView.findViewById(R.id.addfile);
        //上传模块
        uploadFile = (LinearLayout) conferenceView.findViewById(R.id.uploadFile);
        //上传图片
        uppic = (LinearLayout) conferenceView.findViewById(R.id.uppic);
        upphoto = (LinearLayout) conferenceView.findViewById(R.id.upphoto);
        upfile = (LinearLayout) conferenceView.findViewById(R.id.upfile);
        mune = (LinearLayout) conferenceView.findViewById(R.id.mune);
        persion = (ListView) conferenceView.findViewById(R.id.lv_lvpersion1);
        lv_lvfile2 = (ListView) conferenceView.findViewById(R.id.lv_lvfile2);
        tabfiles = (TextView) conferenceView.findViewById(R.id.tv_tabfiles);
        tabchat = (TextView) conferenceView.findViewById(R.id.tv_tabchat);
        chat_linear = (LinearLayout) findViewById(R.id.chat_container);
        linear_fiel = (LinearLayout) findViewById(R.id.file_linear);
        mDrawerLayout.setScrimColor(getResources().getColor(R.color.translucent));
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        LinearLayout.LayoutParams layoutparams8 = (LinearLayout.LayoutParams) chat_linear.getLayoutParams();
        layoutparams8.width = vm.getDefaultDisplay().getWidth() / 2;
        chat_linear.setLayoutParams(layoutparams8);
        pageViews.add(conferenceView);
        pageViews.add(zoomView);
        viewPager.setAdapter(new ContentPageAdapter(pageViews));
        initVideoStreamsViews();
        fixAllResolution(this.vm, width, height);
    }


    protected boolean backPressed() {
        closeNetTimer();
//        conferenceStreamView.playRemoteStreamId("", checksound);
        if (viewPager.getCurrentItem() == 1) {
            //放大视频的时候
            isExitShareVideo = true;
        }
        viewPager.setCurrentItem(0, false);
        if (progressDialog != null && progressDialog.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                        if (timerTask != null) {
                            timerTask.cancel();
                            timerTask = null;
                        }
                    }
                }
            });
            return false;
        }

        if (meetingScreenGrid.getContainer().getVisibility() != View.VISIBLE) {
            content_frame.setBackgroundColor(getResources().getColor(R.color.gray5));
            if (YCHSConferenceClient.getInstance().hasSharePermission()) {
                final RemoteStream stream = YCHSConferenceClient.getInstance()
                        .getRemoteStreamsById(
                                YCHSConferenceClient.getInstance()
                                        .getJoinResponse()
                                        .getCurrShareStreamId());
                if (stream != null) {
                    final PopDialog popDialog = new PopDialog(
                            ConferenceRoomUI.this);
                    popDialog.setPopMessage("是否结束共享视频?");
                    popDialog.setConfirmOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            meetingScreenGrid.getContainer().setVisibility(View.GONE);
                            conferenceStreamView.playRemoteStream(stream);
                            YCHSConferenceClient.getInstance().stopShare();
                            popDialog.dismiss();
                            isExitShareVideo = true;

                            if (YCHSInstance.getInstance().getRecorderId() != null) {

                                RecordOptions opt = new RecordOptions();
                                opt.setRecorderId(YCHSInstance.getInstance()
                                        .getRecorderId());

                                YCHSConferenceClient.getInstance()
                                        .startRecorder(opt, null);
                                // }

                            }
                        }
                    });
                    popDialog.showAtLocation(content_frame, Gravity.CENTER, 0, 0);
                    return false;
                }
            }
            content_frame.setBackgroundColor(getResources().getColor(R.color.default_person_bg2));
            enlargeFlag = false;
            meetingScreenGrid.getContainer().setVisibility(View.VISIBLE);
            meetingScreenGrid.setLocalCameraViewGone();
            if (isVideoOpen) {
                meetingScreenGrid.updateScreenGrid(YCHSConferenceClient
                        .getInstance().getConferenceClient(), YCHSConferenceClient
                        .getInstance().getUserList());
            }

            fixResolution(vm, width, height);
            if (isVideoOpen) {
                conferenceStreamView.playRemoteStreamId("", checksound);
            }
            return false;
        }
        if (isExitShareVideo) {
            isExitShareVideo = false;
            exit();
        } else {
            Log.e("GetTime", isExitShareVideo + "");
            exit();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
       /* int currentItem = viewPager.getCurrentItem();
        if (currentItem == 0) {
            backPressed();
        } else if (currentItem == 1) { //放大界面
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isExitShareVideo = false;
                    fixResolution(vm, width, height);
                    ViewGroup parent = (ViewGroup) conferenceView.getParent();
                    if (parent != null) {
                        parent.removeAllViews();
                    }
                    viewPager.addView(conferenceView, 0);
                    zoomStreamView.stopRemoteStream();
                    backPressed();
                }
            });
        }*/

    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        YCHSConferenceClient.getInstance().setMeetingId(intent.getStringExtra(MEETING_ID));
        YCHSConferenceClient.getInstance().setMCURole(intent.getStringExtra(MCU_ROLE));
        YCHSConferenceClient.getInstance().setMCURoomId(intent.getStringExtra(MCU_ROOMID));
        YCHSConferenceClient.getInstance().setMeeting_type(intent.getStringExtra(MEETING_TYPE));
        joinFlag = intent.getStringExtra("joinFlag");
        meetingName = intent.getStringExtra(MEETING_NAME);
        meetingStartTime = intent.getStringExtra(MEETING_SART_TIME);
        confrenceName.setText(meetingName);
        myAdapter = new MyAdapter();
        lv_lvpersion.setAdapter(myAdapter);
        persion.setAdapter(myAdapter);
        applySpeakerList = new ArrayList<String>();
        fileList = new ArrayList<FileEntity>();
        fileAdapter = new FileAdapter();
        lv_lvfile.setAdapter(fileAdapter);
        updateAttacheFiles();
        lv_lvfile2.setAdapter(fileAdapter);

        persion.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                String role = YCHSConferenceClient.getInstance().getMCURole();
                // 只有主持人和助理可以进入
                if (YCHSConferenceClient.ROLE_PRESENTER.equals(role)
                        || YCHSConferenceClient.ROLE_ASSISTANT.equals(role)) {
                    String loginUserCode = YCHSInstance.getInstance()
                            .getLoginUser().getUSER_CODE();
                    String tempUserCode = YCHSConferenceClient.getInstance()
                            .getUserList().get(arg2).getUserSN();
                    // 当点击的不是自己的名称,和点击的不是主持人
                    if (!loginUserCode.equals(tempUserCode)
                            && !YCHSConferenceClient.ROLE_PRESENTER
                            .equals(YCHSConferenceClient.getInstance()
                                    .getUserList().get(arg2).getRole())) {
                        Intent intent = new Intent(ConferenceRoomUI.this,
                                MettingEditActivity.class);
                        intent.putExtra("position", arg2);
                        startActivityForResult(intent, EDIT_METTING);
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_PIC_FROM_CAMERA:
                if (resultCode == Activity.RESULT_OK) {
                    // ImageZip.ipImage(mFile.getAbsolutePath());//压缩图片
                    // mImageViewPhoto.setImageURI(Uri.fromFile(mFile));
                    Log.d(TAG, "onActivityResult: camera upload start");
                    uploadFile();
                }

                // localStream.enableVideo();
                SwitchToIOThread.getInstance().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        localStream.enableVideo();
                    }
                }, 1000);
                isOpenCameraOrNot = true;
                break;
            case GET_PIC_FROM_GALLERY:
                if (resultCode == Activity.RESULT_OK) {
                    // getImageFromGallery(data);
                    Uri selectedImage = data.getData();
                    // 用一个String数组存储相册所有图片
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    // 用一个Cursor对象的到相册的所有内容
//                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    Cursor cursor = ResolverUtil.getResolver(ConferenceRoomUI.this, selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    // 得到选中图片下标
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    // 得到所选的相片路径
                    String picturePath = cursor.getString(columnIndex);
                    // 关闭Cursor，以免占用资源
                    cursor.close();
//                    try {
//                        mFile = ESAPIUtil.validFilePath2(picturePath);
//                        uploadFile();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        showErrorWithStatus("附件上传失败");
//                    }

                    mFile = APPUtils.getfile(picturePath);
//                    mFile = new File(picturePath);
                    Log.d(TAG, "onActivityResult: album upload start");
                    uploadFile();
                }
                break;

            case EDIT_METTING:
                if (resultCode == 2) {
                    String type = data.getStringExtra("type");
                    String userCode = data.getStringExtra("userCode");
                    String sreamId = data.getStringExtra("streamId");
                    sendForbidTalkSocket(type, userCode, sreamId);
                } else if (resultCode == 3) {
                    String type = data.getStringExtra("type");
                    String userCode = data.getStringExtra("userCode");
                    sendDismissMeetingSocket(type, userCode);
                } else if (resultCode == 4) {
                    String type = data.getStringExtra("type");
                    String userCode = data.getStringExtra("userCode");
                    String role = data.getStringExtra("role");
                    sendChangeUserSocket(type, userCode, role, null, null);
                }
                break;
        }
    }

    private void sendChangeUserSocket(String type, String userCode,
                                      String roleCode, String addVideoUser, String replaceRegion) {
        try {
            JSONObject jobj = new JSONObject();
            jobj.put("type", type);
            jobj.put("sessionid", ConfigUtil.getInstance().getSessionId());
            jobj.put("meetingId", YCHSConferenceClient.getInstance().getMeetingId());
            jobj.put("userCode", userCode);
            jobj.put("roleCode", roleCode);
            jobj.put("addVideoUser", addVideoUser);
            jobj.put("replaceRegion", replaceRegion);

            if ("4".equalsIgnoreCase(roleCode)) {
                isEventUserListener = 0;
            }
            YCHSWebSocketAPI.getInstance().sendSocketMessage(jobj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendDismissMeetingSocket(String type, String userCode) {
        try {
            JSONObject jobj = new JSONObject();
            jobj.put("type", type);
            jobj.put("meetingId", YCHSConferenceClient.getInstance()
                    .getMeetingId());
            jobj.put("sessionid", ConfigUtil.getInstance().getSessionId());
            jobj.put("userCode", userCode);
            YCHSWebSocketAPI.getInstance().sendSocketMessage(jobj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendForbidTalkSocket(String type, String userCode,
                                      String sreamId) {
        try {
            JSONObject jobj = new JSONObject();
            jobj.put("type", type);
            jobj.put("meetingId", YCHSConferenceClient.getInstance().getMeetingId());
            jobj.put("userCode", userCode);
            jobj.put("sessionid", ConfigUtil.getInstance().getSessionId());
            jobj.put("streamId", sreamId);
            jobj.put("controlUserCode", YCHSInstance.getInstance().getLoginUser().getUSER_CODE());
            YCHSWebSocketAPI.getInstance().sendSocketMessage(jobj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void uploadFile() {
//		progressDialog = ProgressDialog.show(this, null, "正在上传附件...");
        //传输进度提示
        final Progress_Dialog progress_dl = new Progress_Dialog(ConferenceRoomUI.this, "正在上传附件...");
//		userSelect.setWidth(bt_showPopupWindow.getWidth());
//		userSelect.showAsDropDown(tv_response, 0, 0);
        progress_dl.showAtLocation(ConferenceRoomUI.this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);

        String meetingId = getIntent().getStringExtra(MEETING_ID);
        //先压缩下
        String filePath = mFile.getPath();
        String compressImage = PictureUtil.compressImage(filePath, filePath, 30);
        File compressedPic = new File(compressImage);
//        String suffix = FileUtil.getFileNameWithSuffix(filePath);
//        if (!FileUtil.suffixConcat(suffix)){
//            ToastUtil.showLong(ConferenceApp.getApp(), "文件类型不符合要求");
//           return;
//        }
        long size = compressedPic.length();
        if (size > 10 * 1024 * 1024) {
            ToastUtil.showLong(ConferenceApp.getApp(), "文件过大");
            return;
        }
        compressedPic.setExecutable(false);
        YCHShttpAPI.postFile(this, meetingId, compressedPic, new StringCallback() {

            @Override
            public void inProgress(float progress) {
                Log.d(TAG, "inProgress: ===" + progress);
                int currentProgress = (int) (progress * 100);
                progress_dl.setProgress(currentProgress);
            }

            @Override
            public void onResponse(String response) {
                OnResponse onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    showInfoWithStatus("附件上传成功!");
                    YCHSWebSocketAPI.getInstance().attacheFile();
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(ConferenceRoomUI.this, TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    showInfoWithStatus("附件上传失败");

                }
                if (progress_dl.isShowing())
                    progress_dl.dismiss();
            }

            @Override
            public void onError(Call call, int statusCode, Exception e) {
                if (progress_dl.isShowing())
                    progress_dl.dismiss();
                showInfoWithStatus("附件上传失败!");
                Log.e("uploadFile error", "statuscode:" + statusCode + "//" + "exception :" + e.getMessage());
            }
        });
    }

    @Override
    protected void initListeners() {
        upView.setOnTouchListener(this);
        rightView.setOnTouchListener(this);
        downView.setOnTouchListener(this);
        leftView.setOnTouchListener(this);
        zoomInView.setOnTouchListener(this);
        zoomOutView.setOnTouchListener(this);


        tabchat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
                lv_lvpersion.setVisibility(View.GONE);
                linear_fiel.setVisibility(View.GONE);
                ll_fileLayout.setVisibility(View.GONE);
            }
        });

        tabfiles.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
                lv_lvpersion.setVisibility(View.GONE);
                linear_fiel.setVisibility(View.VISIBLE);
                ll_fileLayout.setVisibility(View.VISIBLE);
            }
        });

        btn_09.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.e("GetTime", "退出");
//                backPressed();
                persion.setVisibility(View.GONE);
                mune.setVisibility(View.GONE);
                chat_view.setVisibility(View.VISIBLE);
            }
        });


        addfile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (uploadFile.getVisibility() == View.VISIBLE) {
                    uploadFile.setVisibility(View.GONE);
                } else {
                    uploadFile.setVisibility(View.VISIBLE);
                }
            }
        });

        uppic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 向onActivityResult发送intent，requestCode为GET_PIC_FROM_GALLERY
                startActivityForResult(i, GET_PIC_FROM_GALLERY);
            }
        });

        upphoto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                localStream.disableVideo();
                Intent intent = new Intent();
                isOpenCameraOrNot = false;
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                // 确定存储拍照得到的图片文件路径
                mFile = new File(ATTACHEFILEPATH, System.currentTimeMillis() + ".jpg");
                try {
                    mFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 加载Uri型的文件路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                // 向onActivityResult发送intent，requestCode为GET_PIC_FROM_CAMERA
                startActivityForResult(intent, GET_PIC_FROM_CAMERA);
            }
        });

        chatback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (persion.getVisibility() == View.GONE) {
                    persion.setVisibility(View.VISIBLE);
                    mune.setVisibility(View.VISIBLE);
                    chat_view.setVisibility(View.GONE);
                    lv_lvfile2.setVisibility(View.GONE);
//                    YCHSConferenceClient.getApp().getMeetingUserListAlone();
                    myAdapter.notifyDataSetChanged();
                }
            }
        });

        upfile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lv_lvpersion.getVisibility() == View.GONE) {
                    lv_lvfile2.setVisibility(View.VISIBLE);
                    persion.setVisibility(View.GONE);
                    mune.setVisibility(View.GONE);
                    chat_view.setVisibility(View.GONE);
                    updateAttacheFiles();
                }
            }
        });

        btn_01.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("GetTime", "切换摄像头");
                if (YCHSConferenceClient.getInstance().hasSwitchCameraPermission()) {
//                    btn_01.setClickable(false);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            switchCamera();
                        }
                    }).start();

                } else {
                    Toast.makeText(getApplicationContext(), "摄像头权限未打开", Toast.LENGTH_SHORT).show();
                }
            }
        });
       /* btn_03.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (YCHSConferenceClient.getApp().hasAudioPermission()) {
//                    Log.e("GetTime", meetingUser.getAudioStatus());
                    if (meetingUser.getAudioStatus() == null || "addAudioStream".equals(meetingUser.getAudioStatus())) {
                        Log.e("GetTime", "关闭麦克风");
                        ToastUtil.showShort(ConferenceRoomUI.this, "关闭麦克风");
                        closeAudio();
                        btn_03.setClickable(false);
                    } else {
                        Log.e("GetTime", "开启麦克风");
                        ToastUtil.showShort(ConferenceRoomUI.this, "开启麦克风");
                        openAudio();
                        btn_03.setClickable(false);
                    }
                    RefreshView();
                }
            }
        }); */

        btn_03.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (YCHSConferenceClient.getInstance().hasAudioPermission()) {
//                    Log.e("GetTime", meetingUser.getAudioStatus());
//                    final ImageView audio_img = (ImageView) btn_03.findViewById(R.id.audio_img);
                    if (checkMic) {
                        Log.e("GetTime", "关闭麦克风");
                        ToastUtil.showShort(ConferenceRoomUI.this, "关闭麦克风");
                        closePTTAudio();
                        checkMic = false;
                        audio_img.setBackgroundResource(R.drawable.u103);
                        btn_03.setClickable(true);
                    } else {
                        Log.e("GetTime", "开启麦克风");
                        ToastUtil.showShort(ConferenceRoomUI.this, "开启麦克风");
                        openPTTAudio();
                        checkMic = true;
                        audio_img.setBackgroundResource(R.drawable.u102);
                        btn_03.setClickable(true);
                    }
//                    RefreshView();
                }
            }
        });

        btn_06.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if ("1".equals(meetingUser.getRole()) || "2".equals(meetingUser.getRole())) {
                    GetMutAllStaut();
                    if (muta == 0) {
                        muteAll();
                    } else {
                        enableAudioAll();
                    }
                    GetMutAllStaut();
                    RefreshAudioAllview();
                } else {
                    Toast.makeText(ConferenceRoomUI.this, "您不是主持人,暂时无法使用此功能！", Toast.LENGTH_LONG).show();

                }*/
//                Log.e("GetTime", "全部静音");
//                ToastUtil.showShort(getApplicationContext(), "全部静音");
//                btn_06.setClickable(false);
//                tag = v.getTag();
//                Toast.makeText(ConferenceRoomUI.this, (String) v.getTag(), Toast.LENGTH_LONG).show();
                /*if ("0".equals((String) v.getTag())) {
                    muteAll();
                } else {
                    enableAudioAll();
                }*/
//                AudioUtil audioUtil = AudioUtil.getApp(ConferenceRoomUI.this);
//                if (audioUtil.getCallVolume() == 1) {
//                    int callMaxVolume = audioUtil.getCallMaxVolume();
//                    audioUtil.setCallVolume(callMaxVolume - 1);
//                    btn_06.findViewById(R.id.muteall_img1).setBackgroundResource(R.drawable.sound);
//                } else {
//                    audioUtil.setCallVolume(1);
//                    btn_06.findViewById(R.id.muteall_img1).setBackgroundResource(R.drawable.u104);
//                }
//                Log.e("GetTime", audioUtil.getCallVolume() + "");
//                btn_06.setClickable(true);
//                if (YCHSConferenceClient.getApp().hasVideoPermission()) {
                if (isOpenCameraOrNot) {
                    closeVideo();
                    showErrorWithStatus("摄像头已经关闭");
                } else {
                    openVideo();
                    showErrorWithStatus("摄像头已经开启");
                }
//                    if (meetingUser.getVideoStatus() == null || "addVideoStream".equals(meetingUser.getVideoStatus())) {
//                        closeVideo();
//                        showErrorWithStatus("摄像头已经关闭");
////                        video_img.setImageResource(R.drawable.nocamrea);
//                    } else {
//                        openVideo();
//                        showErrorWithStatus("摄像头已经开启");
////                        video_img.setImageResource(R.drawable.camrea);
//                    }
//                }

            }
        });

        btn_07.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //20171124新增视频播放时才能设置音频切换
                if (isVideoOpen) {
                    btn_07.setClickable(false);
                    if (checksound) {
                        checksound = false;
                        if (conferenceStreamView != null && conferenceStreamView.getRemoteStream() != null) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    conferenceStreamView.getRemoteStream().enableAudio();
                                }
                            }).start();

                            Log.e("GetTime", "声音开启");
                            speakerImg.setImageResource(R.drawable.sound);
                        }
                        Toast.makeText(ConferenceRoomUI.this, "声音打开！", Toast.LENGTH_SHORT).show();
                    } else {
                        checksound = true;
                        if (conferenceStreamView != null && conferenceStreamView.getRemoteStream() != null) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    conferenceStreamView.getRemoteStream().disableAudio();
                                }
                            }).start();

                            Log.e("GetTime", "声音关闭");
                            speakerImg.setImageResource(R.drawable.u104);
                        }
                        Toast.makeText(ConferenceRoomUI.this, "声音关闭！", Toast.LENGTH_SHORT).show();
                    }
                    btn_07.setClickable(true);
                } else {
                    Toast.makeText(ConferenceRoomUI.this, "视频还未开启呢！请开启里视频流再来设置静音吧！！", Toast.LENGTH_LONG).show();
                }
            }
        });

        //设置禁言
        btn_10.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /*btn_10.setClickable(false);
                if (!isVideoOpen) {
                    YCHSWebSocketAPI.getApp().contrlMixVideo("open");
                    Toast.makeText(ConferenceRoomUI.this, "远程视频打开", Toast.LENGTH_LONG).show();
                    checksound = true;
                    speakerImg.setImageResource(R.drawable.u104);
                    if (conferenceStreamView != null && conferenceStreamView.getRemoteStream() != null) {
                        conferenceStreamView.getRemoteStream().disableAudio();
                        Log.e("GetTime", "声音关闭");
                    }
                } else {
                    YCHSWebSocketAPI.getApp().contrlMixVideo("close");
                    Toast.makeText(ConferenceRoomUI.this, "远程视频关闭", Toast.LENGTH_LONG).show();
                }
                btn_10.setClickable(true);*/
                Log.e("GetTag", "Tag" + v.getTag());
//                if ("0".equals((String) v.getTag())) {
                if (IsNomute) {
                    muteAll();
                    ToastUtil.showToast("打开全场静音！");
                    speak_img.setImageResource(R.drawable.forbid_talk);

                } else {
                    ToastUtil.showToast("关闭全场静音！");
                    enableAudioAll();

                    speak_img.setImageResource(R.drawable.allow_talk);
                }

            }
        });


        tx_open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);

            }
        });

        iv_open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
                /*runOnUiThread(new Runnable() {
                    @Override
					public void run() {
						toolbar.setVisibility(View.VISIBLE);
						toolbarShowFlag = true;
					}
				});*/
            }
        });
        iv_close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawer(Gravity.LEFT);
            /*	toolbarShowFlag = false;
                delayHideToolBar();*/
            }
        });
        tv_tabusers.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if ("0".equals(tv_tabusers.getTag())) {
                    tv_tabusers.setBackgroundResource(R.drawable.u129);
                    tv_tabfiles.setBackgroundResource(R.drawable.u129_1);
                    tv_tabusers.setTag("1");
                    tv_tabfiles.setTag("0");
                    lv_lvpersion.setVisibility(View.VISIBLE);
                    ll_fileLayout.setVisibility(View.GONE);
                }
            }
        });
        tv_tabfiles.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if ("0".equals(tv_tabfiles.getTag())) {
                    tv_tabusers.setBackgroundResource(R.drawable.u129_1);
                    tv_tabfiles.setBackgroundResource(R.drawable.u129);
                    tv_tabusers.setTag("0");
                    tv_tabfiles.setTag("1");
                    lv_lvpersion.setVisibility(View.GONE);
                    ll_fileLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        ll_tackphoto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                localStream.disableVideo();
                isOpenCameraOrNot = false;
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                // 确定存储拍照得到的图片文件路径
                mFile = new File(ATTACHEFILEPATH, System.currentTimeMillis()
                        + ".jpg");
                isExist(ATTACHEFILEPATH);
                try {
                    mFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 加载Uri型的文件路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                // 向onActivityResult发送intent，requestCode为GET_PIC_FROM_CAMERA
                startActivityForResult(intent, GET_PIC_FROM_CAMERA);
            }
        });

        ll_gallery.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 向onActivityResult发送intent，requestCode为GET_PIC_FROM_GALLERY
                startActivityForResult(i, GET_PIC_FROM_GALLERY);
            }
        });

        lv_lvfile.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                FileEntity fileEntity = fileList.get(arg2);
                final File file = new File(ATTACHEFILEPATH, fileEntity.getFileName());
                if (file.exists()) {
                    // 直接打开本地文件
//                    openAttacheFile(file);
//                    openAssignFolder(ATTACHEFILEPATH);
                    try {
                        startActivity(AndroidFileUtil.openFile(file.getPath()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e("GetTime", ATTACHEFILEPATH);
                } else {

                    final Progress_Dialog progress_dl = new Progress_Dialog(ConferenceRoomUI.this, "正在下载附件...");
//		userSelect.setWidth(bt_showPopupWindow.getWidth());
//		userSelect.showAsDropDown(tv_response, 0, 0);
                    progress_dl.showAtLocation(ConferenceRoomUI.this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                    // 下载服务器文件
                    YCHShttpAPI.downLoadFile(ConferenceRoomUI.this, fileEntity.getFileId(), new FileCallBack(ATTACHEFILEPATH, fileEntity.getFileName()) {
                        @Override
                        public void onResponse(File response) {
                            if (progress_dl.isShowing())
                                progress_dl.dismiss();
                            showWithStatus("文件下载成功!文件路径：文件管理/本地/ychs_files" + file.getName());
                            try {
                                startActivity(AndroidFileUtil.openFile(file.getPath()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Call call, int statusCode, Exception e) {
                            showInfoWithStatus("文件下载失败!");
                            if (progress_dl.isShowing())
                                progress_dl.dismiss();
                        }

                        @Override
                        public void inProgress(float progress) {
//                            System.out.println("文件下载进度:" + (int) (100 * progress));
                            int p = (int) (100 * progress);
                            Log.d("file", "文件下载进度:" + p);
                            progress_dl.setProgress(p);
                        }
                    });

                }
            }
        });

        lv_lvfile2.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                final FileEntity fileEntity = fileList.get(arg2);
                final File file = new File(ATTACHEFILEPATH, fileEntity.getFileName());
                if (file.exists()) {
                    // 直接打开本地文件
//                    openAttacheFile(file);
//                    openAssignFolder(ATTACHEFILEPATH);
                    try {
                        startActivity(AndroidFileUtil.openFile(file.getPath()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e("GetTime", ATTACHEFILEPATH);
                } else {

                    final Progress_Dialog progress_dl = new Progress_Dialog(
                            ConferenceRoomUI.this, "正在下载附件...");
//		userSelect.setWidth(bt_showPopupWindow.getWidth());
//		userSelect.showAsDropDown(tv_response, 0, 0);
                    progress_dl.showAtLocation(ConferenceRoomUI.this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                    // 下载服务器文件
                    YCHShttpAPI.downLoadFile(ConferenceRoomUI.this, fileEntity.getFileId(), new FileCallBack(ATTACHEFILEPATH, fileEntity.getFileName()) {
                        @Override
                        public void onResponse(File response) {
                            Log.d(TAG, "下载完成1:" + FileSizeUtil.getFilesize(file));
                            Log.d(TAG, "下载完成2:" + FileSizeUtil.getAutoFileOrFilesSize(file.getPath()));
//                            if (fileEntity.getSize().equalsIgnoreCase(FileSizeUtil.getFilesize(file))) {
                            if (progress_dl.isShowing())
                                progress_dl.dismiss();
                            fileAdapter.notifyDataSetChanged();
                            showWithStatus("文件下载成功!文件路径：文件管理/本地/ychs_files" + file.getName());
                            try {
                                startActivity(AndroidFileUtil.openFile(file.getPath()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
//                            } else {
//                                showErrorWithStatus("文件下载不全,请重新下载!!");
//                                if (file.isFile() && file.exists()) {
//                                    file.delete();
//                                }
//                                fileAdapter.notifyDataSetChanged();
//                            }

                        }

                        @Override
                        public void onError(Call call, int statusCode, Exception e) {
                            Log.e(TAG, "onError: ", e);
                            showInfoWithStatus("文件下载失败!");
                            if (file.isFile() && file.exists()) {
                                file.delete();
                            }
                            if (progress_dl.isShowing())
                                progress_dl.dismiss();
                        }

                        @Override
                        public void inProgress(float progress) {
                            int p = (int) (100 * progress);
                            Log.d("file", "文件下载进度:" + p);
                            progress_dl.setProgress(p);
                        }
                    });
//                    String url = "http://172.28.1.150:13889/service/DownloadFile?time=2020-04-21 12:22:47.961&fileId=5c30a1e0-ff60-406f-9e49-0d6a6e58d0a3&sessionid=rMDsxFt6t9J1TgatECjSJzNH8BOXhQpm";
//                    FormBody.Builder builder = new FormBody.Builder();
//                    builder.add("time","2020-04-21 12:22:47.961");
//                    builder.add("fileId","5c30a1e0-ff60-406f-9e49-0d6a6e58d0a3");
//                    builder.add("sessionid","rMDsxFt6t9J1TgatECjSJzNH8BOXhQpm");
//                    FormBody formBody = builder.build();
//                    Request request = new Request.Builder().url(url).build();
//                    OkHttpClient client = new OkHttpClient();
//                    client.newCall(request).enqueue(new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                            Log.e(TAG, "onFailure: ", e);
//                        }
//
//                        @Override
//                        public void onResponse(Call call, Response response) throws IOException {
//                            Sink sink = null;
//                            BufferedSink bufferedSink = null;
//                            String mSDCardPath= Environment.getExternalStorageDirectory().getAbsolutePath();//SD卡路
//                            File dest = new File(mSDCardPath ,fileEntity.getFileName());
//                            sink = Okio.sink(dest);
//                            bufferedSink = Okio.buffer(sink);
//                            bufferedSink.writeAll(response.body().source());
//                            bufferedSink.close();
//                            Log.d(TAG, "onResponse: ");
//                        }
//                    });
                }
            }
        });

//		mDrawerLayout.setDrawerListener(new DrawerListener() {
//			/**
//			 * 当抽屉滑动状态改变的时候被调用 状态值是STATE_IDLE（闲置--0）, STATE_DRAGGING（拖拽的--1）,
//			 * STATE_SETTLING（固定--2）中之一。
//			 * 抽屉打开的时候，点击抽屉，drawer的状态就会变成STATE_DRAGGING，然后变成STATE_IDLE
//			 */
//			@Override
//			public void onDrawerStateChanged(int arg0) {
//				Log.i("drawer", "drawer的状态：" + arg0);
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						toolbar.setVisibility(View.VISIBLE);
//					}
//				});
//			}
//
//			/**
//			 * 当抽屉被滑动的时候调用此方法 arg1 表示 滑动的幅度（0-1）
//			 */
//			@Override
//			public void onDrawerSlide(View arg0, float arg1) {
//				Log.i("drawer", arg1 + "");
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						toolbar.setVisibility(View.VISIBLE);
//					}
//				});
//			}
//
//			/**
//			 * 当一个抽屉被完全打开的时候被调用
//			 */
//			@Override
//			public void onDrawerOpened(View arg0) {
//				iv_open.setVisibility(View.GONE);
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						toolbar.setVisibility(View.VISIBLE);
//						toolbarShowFlag = true;
//					}
//				});
//			}
//
//			/**
//			 * 当一个抽屉完全关闭的时候调用此方法
//			 */
//			@Override
//			public void onDrawerClosed(View arg0) {
//				iv_open.setVisibility(View.VISIBLE);
//				delayHideToolBar();
//				toolbarShowFlag = false;
//			}
//		});

        mConferenceChatView.getChat2User().setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final UserSelectDialog userSelect = new UserSelectDialog(
                                ConferenceRoomUI.this);
                        userSelect.setListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int position, long id) {
                                MeetingUser user = (MeetingUser) parent.getAdapter().getItem(position);
                                mConferenceChatView.setChat2User(user);
                                userSelect.dismiss();
                            }
                        });
                        userSelect.showAtLocation(content_frame,
                                Gravity.CENTER, 0, 0);
                    }
                });
    }

//    private void GetMutAllStaut() {
//        YCHShttpAPI.GetTempRoomStatus(ConferenceRoomUI.this, YCHSConferenceClient.getInstance().getMeetingId(), new StringCallback() {
//
//            @Override
//            public void onResponse(String response) {
//                // TODO Auto-generated method stub
//                try {
//                    JSONObject json = new JSONObject(response);
//                    int resultCode = json.getInt("resultCode");
////                    String  theSpeakerCode = json.getString("theSpeakerCode");
////                    int lock = json.getInt("lock");
////                    int mode = json.getInt("mode");
//                    int muteAll = json.getInt("muteAll");
//                    Log.e("GetTime", resultCode + "-----" + muteAll + "");
//                    muta = muteAll;
//                    if (resultCode == 0) {
//                     /*   if(lock==1){
//                            lockName.setText("解锁互动");
//                            btn_lockroom.setTag("0");
//                            lock_img.setBackgroundResource(R.drawable.roomlock);
//                        }
//                        if(mode==1){
//                            modeName.setText("自由模式");
//                            btn_freemodel.setTag("2");
//                            btn_closeallvideo.setEnabled(false);
//                            muteall_img.setBackgroundResource(R.drawable.u218);
//                            mode_img.setBackgroundResource(R.drawable.zxmode);
//                        }*/
//                       /* if (muteAll == 1) {
////                            muteall_name.setText("取消静音");
////                            muteall_img.setBackgroundResource(R.drawable.mute);
////                            btn_closeallvideo.setTag("1");
//                            muta = muteAll;
//                        }*/
////                        YCHSInstance.getApp().setMode(mode);
//                    }
//                } catch (JSONException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onError(Call call, int statusCode, Exception e) {
//                // TODO Auto-generated method stub
//
//            }
//        });
//
//
//    }

    private void RefreshView(String audioStatus) {

//        final TextView audio_text = (TextView) btn_03.findViewById(R.id.audio_text);
        final ImageView audio_img = (ImageView) btn_03.findViewById(R.id.audio_img);
        if (meetingUser != null) {
            if ("addAudioStream".equals(audioStatus)) {
                Log.e("AudioStream", meetingUser.getAudioStatus() + "关闭麦克风");
//                audio_text.setText("关闭麦克风");
                audio_img.setBackgroundResource(R.drawable.u102);
            } else {
                Log.e("AudioStream", meetingUser.getAudioStatus() + "开启麦克风");
//                audio_text.setText("打开麦克风");
                audio_img.setBackgroundResource(R.drawable.u103);
            }
        }
        btn_03.setClickable(true);

    }

    private void initIconView() {
        final ImageView audio_img = (ImageView) btn_03.findViewById(R.id.audio_img);
        if (meetingUser == null) {
            Toast.makeText(ConferenceRoomUI.this, "meetingUser null", Toast.LENGTH_LONG).show();
            return;
        }
//        ToastUtil.showLong(ConferenceRoomUI.this,meetingUser.getAudioStatus());
       /* if (meetingUser.getAudioStatus() == null || "addAudioStream".equals(meetingUser.getAudioStatus())) {
            audio_img.setBackgroundResource(R.drawable.u102);
        } else {
            audio_img.setBackgroundResource(R.drawable.u103);
        }*/

        if ("1".equals(meetingUser.getRole()) || "2".equals(meetingUser.getRole())) {
            btn_10.setVisibility(View.VISIBLE);
        } else {
            btn_10.setVisibility(View.GONE);
        }

//        if (checkMic) {
//            audio_img.setBackgroundResource(R.drawable.u102);
//        } else {
//            audio_img.setBackgroundResource(R.drawable.u103);
//        }


    }

    /*private void RefreshAudioAllview() {
        final ImageView muteall_img = (ImageView) btn_06.findViewById(R.id.muteall_img1);
        final TextView muteall_text = (TextView) btn_06.findViewById(R.id.muteall_text1);
        if (1 == muta) {
            Toast.makeText(ConferenceRoomUI.this, "取消静音", Toast.LENGTH_LONG).show();
            muteall_img.setBackgroundResource(R.drawable.sound);
//            muteall_text.setText("取消静音");
        } else {
            Toast.makeText(ConferenceRoomUI.this, "全部静音", Toast.LENGTH_LONG).show();
            muteall_img.setBackgroundResource(R.drawable.u104);
//            muteall_text.setText("全部静音");

        }
    }*/

//    Room_Menu room_Menu;

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (lv_lvfile2.getVisibility() == View.VISIBLE) {
                    persion.setVisibility(View.VISIBLE);
                    mune.setVisibility(View.VISIBLE);
                    chat_view.setVisibility(View.GONE);
                    lv_lvfile2.setVisibility(View.GONE);
                    return;
                }/*else{
                    backPressed();
                }*/
                IsOut = true;
                Logoutdialog();
//                backPressed();
//                backPressed();
                break;

            case R.id.content_frame:
//            /*toolbar.setVisibility(View.VISIBLE);
//            delayHideToolBar();*/
//                Toast.makeText(ConferenceRoomUI.this, "屏幕点击", Toast.LENGTH_LONG).show();
//                break;
//            case R.id.iv_menu_room:
//                if (meetingUser != null) {
//                    room_Menu = new Room_Menu(this, itemsOnClick, meetingUser);
//                    Rect rectangle = new Rect();
//                    Window window = getWindow();
//                    window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
//                    int yPos = iv_menu_room.getHeight() + rectangle.top;
//                    room_Menu.showAtLocation(iv_menu_room, Gravity.RIGHT
//                            | Gravity.TOP, 0, yPos);
//                    room_Menu.setOutsideTouchable(false);
//                }
                break;
            case R.id.zoomView:
                mLastTime = mCurTime;
                mCurTime = System.currentTimeMillis();
                if (mCurTime - mLastTime < 300) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isExitShareVideo = false;
                            fixResolution(vm, width, height);
                            ViewGroup parent = (ViewGroup) conferenceView.getParent();
                            if (parent != null) {
                                parent.removeAllViews();
                            }
                            viewPager.addView(conferenceView, 0);
                            zoomStreamView.stopRemoteStream();
                            backPressed();
                        }
                    });
                }
                break;
            case R.id.llRemoteView:
               /* mLastTime = mCurTime;
                mCurTime = System.currentTimeMillis();
                if (mCurTime - mLastTime < 300) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isExitShareVideo = false;
//                            backPressed();
                        }
                    });
                }*/ /*
             * else { runOnUiThread(new Runnable() {
             *
             * @Override public void run() {
             * toolbar.setVisibility(View.VISIBLE); delayHideToolBar(); } }); }
             */
            default:
                break;
        }

    }

    private void Logoutdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ConferenceRoomUI.this);
        builder.setMessage("是否要退出互动室？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //leave();
                backPressed();
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

    }

    // 为弹出窗口实现监听类
//    private OnClickListener itemsOnClick = new OnClickListener() {
//        @SuppressLint("NewApi")
//        public void onClick(View v) {
////            room_Menu.dismiss();
//            String mcu_role = YCHSConferenceClient.getApp().getMCURole();
//            switch (v.getId()) {
//                case R.id.btn_joinhome:
//                    final String alisName = aliasNameDialog.getInvite_code_input().getText()
//                            .toString();
//                    aliasNameDialog.dismiss();
//
//                    if (TextUtils.isEmpty(alisName)) {
//                        Toast.makeText(ConferenceRoomUI.this, "请输入别名", Toast.LENGTH_SHORT).show();
//                        aliasNameDialog.getInvite_code_input().requestFocus();
//                        return;
//                    }
//                    if (mUserSN == null) {
//                        Toast.makeText(ConferenceRoomUI.this, "修改失败，没有获得到当前修改用户名称！", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                    String meetingId = YCHSConferenceClient.getApp().getMeetingId();
//                    YCHSWebSocketAPI.getApp().editAliasName(meetingId, mUserSN, alisName);
//                    break;
//                case R.id.btn_01:// 点击切换摄像头
//                    if (YCHSConferenceClient.getApp()
//                            .hasSwitchCameraPermission()) {
//                        switchCamera();
//                    }
//                    break;
//                case R.id.btn_02:// 关闭视频
//                    if (YCHSConferenceClient.getApp().hasVideoPermission()) {
//                        if (meetingUser.getVideoStatus() == null
//                                || "addVideoStream".equals(meetingUser
//                                .getVideoStatus())) {
//                            closeVideo();
//                        } else {
//                            openVideo();
//                        }
//                    }
//                    break;
//                case R.id.btn_03:// 关闭音频
//                    if (YCHSConferenceClient.getApp().hasAudioPermission()) {
//                        if (meetingUser.getAudioStatus() == null
//                                || "addAudioStream".equals(meetingUser
//                                .getAudioStatus())) {
//                            closeAudio();
//                        } else {
//                            openAudio();
//                        }
//                    }
//                    break;
//                case R.id.btn_05:// 自由模式/主席模式
//                    YCHSWebSocketAPI.getApp().meetingModeSetting(
//                            YCHSConferenceClient.getApp().getMeetingId(),
//                            (String) v.getTag());
//                    break;
//                case R.id.btn_06:// 全部静音
//                    if ("0".equals((String) v.getTag())) {
//                        muteAll();
//                    } else {
//                        enableAudioAll();
//                    }
//                    break;
//            /*
//             * case R.id.btn_04:// 申请主讲 Toast.makeText(MeetingRoomUI.this,
//			 * "申请主讲", Toast.LENGTH_SHORT).show(); break; case R.id.btn_05://
//			 * 自由模式 Toast.makeText(MeetingRoomUI.this, "自由模式",
//			 * Toast.LENGTH_SHORT).show(); break; case R.id.btn_06:// 全部静音
//			 * Toast.makeText(MeetingRoomUI.this, "后期开发",
//			 * Toast.LENGTH_SHORT).show(); break; /*case R.id.btn_07:// 共享
//			 * Toast.makeText(MeetingRoomUI.this, "共享",
//			 * Toast.LENGTH_SHORT).show(); break;
//			 */
//                case R.id.btn_08:// 锁定互动室
//                    YCHSWebSocketAPI.getApp().lockMeetingRoom(
//                            YCHSConferenceClient.getApp().getMeetingId(),
//                            (String) v.getTag());
//                    break;
//                case R.id.btn_09:// 退出
//                    backPressed();
//                    // exit();
//                    break;
//                case R.id.btn_10:// 关闭和打开远程视频流
//                    if (!isVideoOpen) {
//                        YCHSWebSocketAPI.getApp().contrlMixVideo("open");
//                        Toast.makeText(ConferenceRoomUI.this, "远程视频打开", Toast.LENGTH_LONG).show();
//                    } else {
//                        YCHSWebSocketAPI.getApp().contrlMixVideo("close");
//                        Toast.makeText(ConferenceRoomUI.this, "远程视频关闭", Toast.LENGTH_LONG).show();
//                    }
//                    break;
//            }
//        }
//    };

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            //如果是按下
            status = "start";
            setContrlDevice(view);
        }
        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            //如果是松开
            status = "stop";
            setContrlDevice(view);
        }

        return false;
    }

    private void setContrlDevice(View view) {
        switch (view.getId()) {
            case R.id.upView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "turnup", userCode);
                break;
            case R.id.rightView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "turnright", userCode);
                break;
            case R.id.downView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "turndown", userCode);
                break;
            case R.id.leftView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "turnleft", userCode);
                break;
            case R.id.zoomInView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "zoomout", userCode);
                break;
            case R.id.zoomOutView:
                YCHSConferenceClient.getInstance().setContrlDevice(status, "zoomin", userCode);
                break;
        }
    }

    private class FileAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return fileList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = ConferenceRoomUI.this.getLayoutInflater()
                        .inflate(R.layout.item_addmeetfiles, null);
            }
            FileEntity fileEntity = fileList.get(position);
            TextView fileNameView = (TextView) convertView
                    .findViewById(R.id.tv_filename);
            ImageView fileImageView = (ImageView) convertView
                    .findViewById(R.id.iv_fileimg);
            if (fileEntity != null) {
                fileNameView.setText(fileEntity.getFileName());
                File file = new File(ATTACHEFILEPATH, fileEntity.getFileName());
                if (file.exists()) {
                    fileImageView.setImageResource(R.drawable.u130_1);
                    convertView.setTag("1");
                } else {
                    fileImageView.setImageResource(R.drawable.u130_0);
                    convertView.setTag("0");
                }
            }
            return convertView;
        }

    }


    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return YCHSConferenceClient.getInstance().getUserList().size();
        }

        @Override
        public Object getItem(int position) {
            return YCHSConferenceClient.getInstance().getUserList().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            final MeetingUser user = (MeetingUser) getItem(position);
            if (convertView == null) {
                convertView = ConferenceRoomUI.this.getLayoutInflater()
                        .inflate(R.layout.item_addmeetpersion, null);
            }
//            if (user.getUserSN().equals(
//                    YCHSInstance.getApp().getLoginUser().getUSER_CODE())) {
//                String talkStatus = user.getTalkStatus();
//                if (talkStatus != null && "forbidTalkStream".equals(talkStatus)) {
//                    mConferenceChatView.setForbidTalk();
//                } else {
//                    mConferenceChatView.setAllowTalk();
//                }
//            }
            TextView textView1 = (TextView) convertView
                    .findViewById(R.id.textView1);
            ImageView user_img = (ImageView) convertView
                    .findViewById(R.id.user_img);
            ImageView user_role = (ImageView) convertView
                    .findViewById(R.id.user_role);
            final ImageView cb_audio = (ImageView) convertView
                    .findViewById(R.id.cb_audio);
            final ImageView cb_video = (ImageView) convertView
                    .findViewById(R.id.cb_video);

            RelativeLayout personrl = (RelativeLayout) convertView
                    .findViewById(R.id.person_rl);
            if (YCHSConferenceClient.getInstance()
                    .hasConferenceControlPermission()) {
                if ((YCHSInstance.getInstance().getLoginUser().getUSER_CODE()).equals(user.getUserSN())) {
                    if (user.getAudioStatus() == null
                            || "addAudioStream".equals(user.getAudioStatus())) {
                        cb_audio.setImageResource(R.drawable.u1);
                    } else {
                        cb_audio.setImageResource(R.drawable.u111);
                    }
                    if (user.getVideoStatus() == null
                            || "addVideoStream".equals(user.getVideoStatus())) {
                        cb_video.setImageResource(R.drawable.u02);
                    } else {
                        cb_video.setImageResource(R.drawable.u223);
                    }
                }
                switch (user.getRole()) {
                    case YCHSConferenceClient.ROLE_PRESENTER:
                        user_img.setImageResource(R.drawable.perenter);
                        user_role.setVisibility(View.GONE);
                        cb_audio.setVisibility(View.GONE);
                        cb_video.setVisibility(View.GONE);
                        break;
                    case YCHSConferenceClient.ROLE_ASSISTANT:
                        user_img.setImageResource(R.drawable.assistan);
                        user_role.setVisibility(View.GONE);
                        cb_audio.setVisibility(View.GONE);
                        cb_video.setVisibility(View.GONE);
                        break;
                    case YCHSConferenceClient.ROLE_PARTICIPANTS:
                        user_img.setImageResource(R.drawable.participant);
                        user_role.setVisibility(View.GONE);
                        cb_audio.setVisibility(View.VISIBLE);
                        cb_video.setVisibility(View.VISIBLE);
                        break;
                    case YCHSConferenceClient.ROLE_LISTENER:
                        user_img.setImageResource(R.drawable.listener);
                        user_role.setVisibility(View.GONE);
                        cb_audio.setVisibility(View.VISIBLE);
                        cb_video.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            } else {
                switch (user.getRole()) {
                    case YCHSConferenceClient.ROLE_PRESENTER:
                        user_img.setImageResource(R.drawable.perenter);
                        break;
                    case YCHSConferenceClient.ROLE_ASSISTANT:
                        user_img.setImageResource(R.drawable.assistan);
                        break;
                    case YCHSConferenceClient.ROLE_PARTICIPANTS:
                        user_img.setImageResource(R.drawable.participant);
                        break;
                    case YCHSConferenceClient.ROLE_LISTENER:
                        user_img.setImageResource(R.drawable.listener);
                        break;
                    default:
                        break;
                }
                user_role.setVisibility(View.GONE);
                cb_audio.setVisibility(View.GONE);
                cb_video.setVisibility(View.GONE);
            }
            cb_audio.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (user.getAudioStatus() == null
                            || "addAudioStream".equals(user.getAudioStatus())) {
                        cb_audio.setImageResource(R.drawable.u111);
                        user.setAudioStatus("0");
                        YCHSWebSocketAPI.getInstance().deleteAudioStream(
                                YCHSConferenceClient.getInstance()
                                        .getMeetingId(), user.getUserSN());
                        // YCHSWebSocketAPI.getApp().changeHostAssistList(meetingId,
                        // "deleteAudioStream");
                    } else {
                        cb_audio.setImageResource(R.drawable.u1);
                        // user.setAudioStatus("1");
                        YCHSWebSocketAPI.getInstance().addAudioStream(
                                YCHSConferenceClient.getInstance()
                                        .getMeetingId(), user.getUserSN());
                        // YCHSWebSocketAPI.getApp().changeHostAssistList(meetingId,
                        // "addAudioStream");
                    }

                }

            });
            cb_video.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (user.getVideoStatus() == null
                            || "addVideoStream".equals(user.getVideoStatus())) {
                        cb_video.setImageResource(R.drawable.u223);
                        user.setVideoStatus("0");
                        YCHSWebSocketAPI.getInstance().deleteVideoStream(
                                YCHSConferenceClient.getInstance()
                                        .getMeetingId(), user.getUserSN());
                        // YCHSWebSocketAPI.getApp().changeHostAssistList(meetingId,
                        // "deleteVideoStream");
                    } else {
                        cb_video.setImageResource(R.drawable.u02);
                        user.setVideoStatus("1");
                        YCHSWebSocketAPI.getInstance().addVideoStream(
                                YCHSConferenceClient.getInstance()
                                        .getMeetingId(), user.getUserSN());
                        // YCHSWebSocketAPI.getApp().changeHostAssistList(meetingId,
                        // "addVideoStream");
                    }

                }

            });

            if (ConfigUtil.getInstance().getLoginUser().getUSER_CODE().equals(user.getUserSN())) {
                personrl.setBackgroundResource(R.color.gray2);
            } else {
                personrl.setBackgroundResource(R.color.gray);
            }
            textView1.setText(user.getName() + "-" + user.getOrgName());
            return convertView;
        }
    }


    // control

    // 切换摄像头
    private void switchCamera() {
        if (localStream != null && isOpenCameraOrNot == true) {
            localStream.switchCamera(new ActionCallback<Boolean>() {
                @Override
                public void onFailure(WoogeenException arg0) {
//                    btn_01.setClickable(true);
                    Toast.makeText(getApplicationContext(), "切换摄像头失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(Boolean arg0) {
//                    btn_01.setClickable(true);
                    Toast.makeText(getApplicationContext(), "切换摄像头成功", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Log.d(TAG, "switchCamera: " + Thread.currentThread().getName());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "本地视频流获取失败或者摄像头关闭", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void localStreamAudioStatus(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (ADD_AUDIO_STREAM.equals(status)) {
                    localStream.enableAudio();
                    checkMic = true;
                    audio_img.setBackgroundResource(R.drawable.u102);
                    YCHSWebSocketAPI.getInstance().changeHostAssistList(
                            YCHSConferenceClient.getInstance().getMeetingId(),
                            "addAudioStream", meetingUser.getUserSN());
                } else if (DELETE_AUDIO_STREAM.equals(status)) {
                    localStream.disableAudio();
                    checkMic = false;
                    audio_img.setBackgroundResource(R.drawable.u103);
                    YCHSWebSocketAPI.getInstance().changeHostAssistList(
                            YCHSConferenceClient.getInstance().getMeetingId(),
                            "deleteAudioStream", meetingUser.getUserSN());
                }
            }
        });
    }

    // 关闭/打开音频
    private void openAudio() {

        localStream.enableAudio();
        audio_img.setBackgroundResource(R.drawable.u102);
        checkMic = true;
        YCHSWebSocketAPI.getInstance().changeHostAssistList(
                YCHSConferenceClient.getInstance().getMeetingId(),
                "addAudioStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    private void closeAudio() {

        localStream.disableAudio();
        audio_img.setBackgroundResource(R.drawable.u103);
        checkMic = false;
        YCHSWebSocketAPI.getInstance().changeHostAssistList(
                YCHSConferenceClient.getInstance().getMeetingId(),
                "deleteAudioStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    // 关闭/打开音频
    private void openPTTAudio() {
        if (localStream != null && meetingUser != null) {
            Log.d("------", "开启音频");
            localStream.enableAudio();
            YCHSWebSocketAPI.getInstance().changeHostAssistList(
                    YCHSConferenceClient.getInstance().getMeetingId(),
                    "addAudioStream", meetingUser.getUserSN());
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    private void closePTTAudio() {
        if (localStream != null && meetingUser != null) {
            Log.d("------", "关掉音频");
            localStream.disableAudio();
            YCHSWebSocketAPI.getInstance().changeHostAssistList(
                    YCHSConferenceClient.getInstance().getMeetingId(),
                    "deleteAudioStream", meetingUser.getUserSN());
        }
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
    }

    //关闭远程视频
    private void closeAllVideo() {
        YCHSWebSocketAPI.getInstance().contrlMixVideo("close");
    }


    private void localStreamVideoStatus(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (ADD_VIDEO_STREAM.equals(status)) {
                    localStream.enableVideo();
                    video_img.setImageResource(R.drawable.camrea);
                    YCHSWebSocketAPI.getInstance().changeHostAssistList(
                            YCHSConferenceClient.getInstance().getMeetingId(),
                            "addVideoStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
                    isOpenCameraOrNot = true;
                } else if (DELETE_VIDEO_STREAM.equals(status)) {
                    localStream.disableVideo();
                    video_img.setImageResource(R.drawable.nocamrea);
                    YCHSWebSocketAPI.getInstance().changeHostAssistList(
                            YCHSConferenceClient.getInstance().getMeetingId(),
                            "deleteVideoStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
                    isOpenCameraOrNot = false;
                }
            }
        });
    }

    // 关闭/打开视频
    private void openVideo() {
        // localStream.disableVideo();
        /*
         * mRoom.pauseVideo(localStream, new ActionCallback<Void>() {
         *
         * @Override public void onFailure(WoogeenException arg0) { // TODO
         * Auto-generated method stub
         *
         * }
         *
         * @Override public void onSuccess(Void arg0) { // TODO Auto-generated
         * method stub
         *
         * } });
         */

        localStream.enableVideo();
        video_img.setImageResource(R.drawable.camrea);
        YCHSWebSocketAPI.getInstance().changeHostAssistList(
                YCHSConferenceClient.getInstance().getMeetingId(),
                "addVideoStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
        isOpenCameraOrNot = true;
    }

    public void closeVideo() {
        localStream.disableVideo();
        video_img.setImageResource(R.drawable.nocamrea);
        YCHSWebSocketAPI.getInstance().changeHostAssistList(
                YCHSConferenceClient.getInstance().getMeetingId(),
                "deleteVideoStream", meetingUser.getUserSN());
//        YCHSConferenceClient.getApp().getMeetingUserListAlone();
        isOpenCameraOrNot = false;
    }

    // 全部静音
    private void muteAll() {
        YCHSWebSocketAPI.getInstance().disableAudio("all", YCHSInstance.getInstance().getLoginUser().getUSER_CODE());
        IsNomute = false;
    }

    //取消静音
    private void enableAudioAll() {
        YCHSWebSocketAPI.getInstance().enableAudio("all", YCHSInstance.getInstance().getLoginUser().getUSER_CODE());
        IsNomute = true;
    }

    // 退出互动
    private void exit() {
        isExit = true;
        unPublishLocalStream();
        // roomHandler.sendEmptyMessage(MSG_UNPUBLISH);
        // roomHandler.sendEmptyMessageDelayed(MSG_ROOM_DISCONNECTED, 2 * 1000);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // conferenceResetTime();
        return super.dispatchTouchEvent(ev);
    }


    public void conferenceRemove() {
        conferenceAutoLogoutHandler.removeCallbacksAndMessages(null);
    }

    private Handler conferenceAutoLogoutHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            conferenceRemove();
            if (msg.what == AUTO_LOGOUT_ACTIVITY) {
                exit();

//                YCHSInstance.resetInstance();
//                YCHSWebSocketAPI.getApp().closeSocket();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                YCHShttpAPI.LogOut(getBaseContext(), new StringCallback() {
                    @Override
                    public void onResponse(String response) {
                    }

                    @Override
                    public void onError(Call call, int statusCode, Exception e) {
                    }
                });
//                ConfigUtil.getApp().clearLoginUser();
                Intent intent = new Intent(getBaseContext(), LoginUI.class);
                startActivity(intent);
                finish();
            }
        }
    };

    /**
     * @param path 文件夹路径
     */
    public static void isExist(String path) {
        File file = new File(path);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            file.mkdir();
        }
    }

//    @Override
//    protected boolean isNeedOperation() {
//        return false;
//    }


}
